fast-import: allow for multiple --import-marks= arguments
[git] / fast-import.c
1 /*
2 (See Documentation/git-fast-import.txt for maintained documentation.)
3 Format of STDIN stream:
4
5   stream ::= cmd*;
6
7   cmd ::= new_blob
8         | new_commit
9         | new_tag
10         | reset_branch
11         | checkpoint
12         | progress
13         ;
14
15   new_blob ::= 'blob' lf
16     mark?
17     file_content;
18   file_content ::= data;
19
20   new_commit ::= 'commit' sp ref_str lf
21     mark?
22     ('author' sp name sp '<' email '>' sp when lf)?
23     'committer' sp name sp '<' email '>' sp when lf
24     commit_msg
25     ('from' sp committish lf)?
26     ('merge' sp committish lf)*
27     file_change*
28     lf?;
29   commit_msg ::= data;
30
31   file_change ::= file_clr
32     | file_del
33     | file_rnm
34     | file_cpy
35     | file_obm
36     | file_inm;
37   file_clr ::= 'deleteall' lf;
38   file_del ::= 'D' sp path_str lf;
39   file_rnm ::= 'R' sp path_str sp path_str lf;
40   file_cpy ::= 'C' sp path_str sp path_str lf;
41   file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf;
42   file_inm ::= 'M' sp mode sp 'inline' sp path_str lf
43     data;
44   note_obm ::= 'N' sp (hexsha1 | idnum) sp committish lf;
45   note_inm ::= 'N' sp 'inline' sp committish lf
46     data;
47
48   new_tag ::= 'tag' sp tag_str lf
49     'from' sp committish lf
50     ('tagger' sp name sp '<' email '>' sp when lf)?
51     tag_msg;
52   tag_msg ::= data;
53
54   reset_branch ::= 'reset' sp ref_str lf
55     ('from' sp committish lf)?
56     lf?;
57
58   checkpoint ::= 'checkpoint' lf
59     lf?;
60
61   progress ::= 'progress' sp not_lf* lf
62     lf?;
63
64      # note: the first idnum in a stream should be 1 and subsequent
65      # idnums should not have gaps between values as this will cause
66      # the stream parser to reserve space for the gapped values.  An
67      # idnum can be updated in the future to a new object by issuing
68      # a new mark directive with the old idnum.
69      #
70   mark ::= 'mark' sp idnum lf;
71   data ::= (delimited_data | exact_data)
72     lf?;
73
74     # note: delim may be any string but must not contain lf.
75     # data_line may contain any data but must not be exactly
76     # delim.
77   delimited_data ::= 'data' sp '<<' delim lf
78     (data_line lf)*
79     delim lf;
80
81      # note: declen indicates the length of binary_data in bytes.
82      # declen does not include the lf preceding the binary data.
83      #
84   exact_data ::= 'data' sp declen lf
85     binary_data;
86
87      # note: quoted strings are C-style quoting supporting \c for
88      # common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn
89      # is the signed byte value in octal.  Note that the only
90      # characters which must actually be escaped to protect the
91      # stream formatting is: \, " and LF.  Otherwise these values
92      # are UTF8.
93      #
94   committish  ::= (ref_str | hexsha1 | sha1exp_str | idnum);
95   ref_str     ::= ref;
96   sha1exp_str ::= sha1exp;
97   tag_str     ::= tag;
98   path_str    ::= path    | '"' quoted(path)    '"' ;
99   mode        ::= '100644' | '644'
100                 | '100755' | '755'
101                 | '120000'
102                 ;
103
104   declen ::= # unsigned 32 bit value, ascii base10 notation;
105   bigint ::= # unsigned integer value, ascii base10 notation;
106   binary_data ::= # file content, not interpreted;
107
108   when         ::= raw_when | rfc2822_when;
109   raw_when     ::= ts sp tz;
110   rfc2822_when ::= # Valid RFC 2822 date and time;
111
112   sp ::= # ASCII space character;
113   lf ::= # ASCII newline (LF) character;
114
115      # note: a colon (':') must precede the numerical value assigned to
116      # an idnum.  This is to distinguish it from a ref or tag name as
117      # GIT does not permit ':' in ref or tag strings.
118      #
119   idnum   ::= ':' bigint;
120   path    ::= # GIT style file path, e.g. "a/b/c";
121   ref     ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT";
122   tag     ::= # GIT tag name, e.g. "FIREFOX_1_5";
123   sha1exp ::= # Any valid GIT SHA1 expression;
124   hexsha1 ::= # SHA1 in hexadecimal format;
125
126      # note: name and email are UTF8 strings, however name must not
127      # contain '<' or lf and email must not contain any of the
128      # following: '<', '>', lf.
129      #
130   name  ::= # valid GIT author/committer name;
131   email ::= # valid GIT author/committer email;
132   ts    ::= # time since the epoch in seconds, ascii base10 notation;
133   tz    ::= # GIT style timezone;
134
135      # note: comments may appear anywhere in the input, except
136      # within a data command.  Any form of the data command
137      # always escapes the related input from comment processing.
138      #
139      # In case it is not clear, the '#' that starts the comment
140      # must be the first character on that line (an lf
141      # preceded it).
142      #
143   comment ::= '#' not_lf* lf;
144   not_lf  ::= # Any byte that is not ASCII newline (LF);
145 */
146
147 #include "builtin.h"
148 #include "cache.h"
149 #include "object.h"
150 #include "blob.h"
151 #include "tree.h"
152 #include "commit.h"
153 #include "delta.h"
154 #include "pack.h"
155 #include "refs.h"
156 #include "csum-file.h"
157 #include "quote.h"
158 #include "exec_cmd.h"
159
160 #define PACK_ID_BITS 16
161 #define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
162 #define DEPTH_BITS 13
163 #define MAX_DEPTH ((1<<DEPTH_BITS)-1)
164
165 struct object_entry
166 {
167         struct object_entry *next;
168         uint32_t offset;
169         uint32_t type : TYPE_BITS,
170                 pack_id : PACK_ID_BITS,
171                 depth : DEPTH_BITS;
172         unsigned char sha1[20];
173 };
174
175 struct object_entry_pool
176 {
177         struct object_entry_pool *next_pool;
178         struct object_entry *next_free;
179         struct object_entry *end;
180         struct object_entry entries[FLEX_ARRAY]; /* more */
181 };
182
183 struct mark_set
184 {
185         union {
186                 struct object_entry *marked[1024];
187                 struct mark_set *sets[1024];
188         } data;
189         unsigned int shift;
190 };
191
192 struct last_object
193 {
194         struct strbuf data;
195         uint32_t offset;
196         unsigned int depth;
197         unsigned no_swap : 1;
198 };
199
200 struct mem_pool
201 {
202         struct mem_pool *next_pool;
203         char *next_free;
204         char *end;
205         uintmax_t space[FLEX_ARRAY]; /* more */
206 };
207
208 struct atom_str
209 {
210         struct atom_str *next_atom;
211         unsigned short str_len;
212         char str_dat[FLEX_ARRAY]; /* more */
213 };
214
215 struct tree_content;
216 struct tree_entry
217 {
218         struct tree_content *tree;
219         struct atom_str *name;
220         struct tree_entry_ms
221         {
222                 uint16_t mode;
223                 unsigned char sha1[20];
224         } versions[2];
225 };
226
227 struct tree_content
228 {
229         unsigned int entry_capacity; /* must match avail_tree_content */
230         unsigned int entry_count;
231         unsigned int delta_depth;
232         struct tree_entry *entries[FLEX_ARRAY]; /* more */
233 };
234
235 struct avail_tree_content
236 {
237         unsigned int entry_capacity; /* must match tree_content */
238         struct avail_tree_content *next_avail;
239 };
240
241 struct branch
242 {
243         struct branch *table_next_branch;
244         struct branch *active_next_branch;
245         const char *name;
246         struct tree_entry branch_tree;
247         uintmax_t last_commit;
248         unsigned active : 1;
249         unsigned pack_id : PACK_ID_BITS;
250         unsigned char sha1[20];
251 };
252
253 struct tag
254 {
255         struct tag *next_tag;
256         const char *name;
257         unsigned int pack_id;
258         unsigned char sha1[20];
259 };
260
261 struct hash_list
262 {
263         struct hash_list *next;
264         unsigned char sha1[20];
265 };
266
267 typedef enum {
268         WHENSPEC_RAW = 1,
269         WHENSPEC_RFC2822,
270         WHENSPEC_NOW,
271 } whenspec_type;
272
273 struct recent_command
274 {
275         struct recent_command *prev;
276         struct recent_command *next;
277         char *buf;
278 };
279
280 /* Configured limits on output */
281 static unsigned long max_depth = 10;
282 static off_t max_packsize = (1LL << 32) - 1;
283 static int force_update;
284 static int pack_compression_level = Z_DEFAULT_COMPRESSION;
285 static int pack_compression_seen;
286
287 /* Stats and misc. counters */
288 static uintmax_t alloc_count;
289 static uintmax_t marks_set_count;
290 static uintmax_t object_count_by_type[1 << TYPE_BITS];
291 static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
292 static uintmax_t delta_count_by_type[1 << TYPE_BITS];
293 static unsigned long object_count;
294 static unsigned long branch_count;
295 static unsigned long branch_load_count;
296 static int failure;
297 static FILE *pack_edges;
298 static unsigned int show_stats = 1;
299 static int global_argc;
300 static const char **global_argv;
301
302 /* Memory pools */
303 static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
304 static size_t total_allocd;
305 static struct mem_pool *mem_pool;
306
307 /* Atom management */
308 static unsigned int atom_table_sz = 4451;
309 static unsigned int atom_cnt;
310 static struct atom_str **atom_table;
311
312 /* The .pack file being generated */
313 static unsigned int pack_id;
314 static struct packed_git *pack_data;
315 static struct packed_git **all_packs;
316 static unsigned long pack_size;
317
318 /* Table of objects we've written. */
319 static unsigned int object_entry_alloc = 5000;
320 static struct object_entry_pool *blocks;
321 static struct object_entry *object_table[1 << 16];
322 static struct mark_set *marks;
323 static const char *export_marks_file;
324 static const char *import_marks_file;
325 static int import_marks_file_from_stream;
326
327 /* Our last blob */
328 static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
329
330 /* Tree management */
331 static unsigned int tree_entry_alloc = 1000;
332 static void *avail_tree_entry;
333 static unsigned int avail_tree_table_sz = 100;
334 static struct avail_tree_content **avail_tree_table;
335 static struct strbuf old_tree = STRBUF_INIT;
336 static struct strbuf new_tree = STRBUF_INIT;
337
338 /* Branch data */
339 static unsigned long max_active_branches = 5;
340 static unsigned long cur_active_branches;
341 static unsigned long branch_table_sz = 1039;
342 static struct branch **branch_table;
343 static struct branch *active_branches;
344
345 /* Tag data */
346 static struct tag *first_tag;
347 static struct tag *last_tag;
348
349 /* Input stream parsing */
350 static whenspec_type whenspec = WHENSPEC_RAW;
351 static struct strbuf command_buf = STRBUF_INIT;
352 static int unread_command_buf;
353 static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
354 static struct recent_command *cmd_tail = &cmd_hist;
355 static struct recent_command *rc_free;
356 static unsigned int cmd_save = 100;
357 static uintmax_t next_mark;
358 static struct strbuf new_data = STRBUF_INIT;
359 static int seen_data_command;
360
361 static void parse_argv(void);
362
363 static void write_branch_report(FILE *rpt, struct branch *b)
364 {
365         fprintf(rpt, "%s:\n", b->name);
366
367         fprintf(rpt, "  status      :");
368         if (b->active)
369                 fputs(" active", rpt);
370         if (b->branch_tree.tree)
371                 fputs(" loaded", rpt);
372         if (is_null_sha1(b->branch_tree.versions[1].sha1))
373                 fputs(" dirty", rpt);
374         fputc('\n', rpt);
375
376         fprintf(rpt, "  tip commit  : %s\n", sha1_to_hex(b->sha1));
377         fprintf(rpt, "  old tree    : %s\n", sha1_to_hex(b->branch_tree.versions[0].sha1));
378         fprintf(rpt, "  cur tree    : %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1));
379         fprintf(rpt, "  commit clock: %" PRIuMAX "\n", b->last_commit);
380
381         fputs("  last pack   : ", rpt);
382         if (b->pack_id < MAX_PACK_ID)
383                 fprintf(rpt, "%u", b->pack_id);
384         fputc('\n', rpt);
385
386         fputc('\n', rpt);
387 }
388
389 static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *);
390
391 static void write_crash_report(const char *err)
392 {
393         char *loc = git_path("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
394         FILE *rpt = fopen(loc, "w");
395         struct branch *b;
396         unsigned long lu;
397         struct recent_command *rc;
398
399         if (!rpt) {
400                 error("can't write crash report %s: %s", loc, strerror(errno));
401                 return;
402         }
403
404         fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
405
406         fprintf(rpt, "fast-import crash report:\n");
407         fprintf(rpt, "    fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
408         fprintf(rpt, "    parent process     : %"PRIuMAX"\n", (uintmax_t) getppid());
409         fprintf(rpt, "    at %s\n", show_date(time(NULL), 0, DATE_LOCAL));
410         fputc('\n', rpt);
411
412         fputs("fatal: ", rpt);
413         fputs(err, rpt);
414         fputc('\n', rpt);
415
416         fputc('\n', rpt);
417         fputs("Most Recent Commands Before Crash\n", rpt);
418         fputs("---------------------------------\n", rpt);
419         for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
420                 if (rc->next == &cmd_hist)
421                         fputs("* ", rpt);
422                 else
423                         fputs("  ", rpt);
424                 fputs(rc->buf, rpt);
425                 fputc('\n', rpt);
426         }
427
428         fputc('\n', rpt);
429         fputs("Active Branch LRU\n", rpt);
430         fputs("-----------------\n", rpt);
431         fprintf(rpt, "    active_branches = %lu cur, %lu max\n",
432                 cur_active_branches,
433                 max_active_branches);
434         fputc('\n', rpt);
435         fputs("  pos  clock name\n", rpt);
436         fputs("  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
437         for (b = active_branches, lu = 0; b; b = b->active_next_branch)
438                 fprintf(rpt, "  %2lu) %6" PRIuMAX" %s\n",
439                         ++lu, b->last_commit, b->name);
440
441         fputc('\n', rpt);
442         fputs("Inactive Branches\n", rpt);
443         fputs("-----------------\n", rpt);
444         for (lu = 0; lu < branch_table_sz; lu++) {
445                 for (b = branch_table[lu]; b; b = b->table_next_branch)
446                         write_branch_report(rpt, b);
447         }
448
449         if (first_tag) {
450                 struct tag *tg;
451                 fputc('\n', rpt);
452                 fputs("Annotated Tags\n", rpt);
453                 fputs("--------------\n", rpt);
454                 for (tg = first_tag; tg; tg = tg->next_tag) {
455                         fputs(sha1_to_hex(tg->sha1), rpt);
456                         fputc(' ', rpt);
457                         fputs(tg->name, rpt);
458                         fputc('\n', rpt);
459                 }
460         }
461
462         fputc('\n', rpt);
463         fputs("Marks\n", rpt);
464         fputs("-----\n", rpt);
465         if (export_marks_file)
466                 fprintf(rpt, "  exported to %s\n", export_marks_file);
467         else
468                 dump_marks_helper(rpt, 0, marks);
469
470         fputc('\n', rpt);
471         fputs("-------------------\n", rpt);
472         fputs("END OF CRASH REPORT\n", rpt);
473         fclose(rpt);
474 }
475
476 static void end_packfile(void);
477 static void unkeep_all_packs(void);
478 static void dump_marks(void);
479
480 static NORETURN void die_nicely(const char *err, va_list params)
481 {
482         static int zombie;
483         char message[2 * PATH_MAX];
484
485         vsnprintf(message, sizeof(message), err, params);
486         fputs("fatal: ", stderr);
487         fputs(message, stderr);
488         fputc('\n', stderr);
489
490         if (!zombie) {
491                 zombie = 1;
492                 write_crash_report(message);
493                 end_packfile();
494                 unkeep_all_packs();
495                 dump_marks();
496         }
497         exit(128);
498 }
499
500 static void alloc_objects(unsigned int cnt)
501 {
502         struct object_entry_pool *b;
503
504         b = xmalloc(sizeof(struct object_entry_pool)
505                 + cnt * sizeof(struct object_entry));
506         b->next_pool = blocks;
507         b->next_free = b->entries;
508         b->end = b->entries + cnt;
509         blocks = b;
510         alloc_count += cnt;
511 }
512
513 static struct object_entry *new_object(unsigned char *sha1)
514 {
515         struct object_entry *e;
516
517         if (blocks->next_free == blocks->end)
518                 alloc_objects(object_entry_alloc);
519
520         e = blocks->next_free++;
521         hashcpy(e->sha1, sha1);
522         return e;
523 }
524
525 static struct object_entry *find_object(unsigned char *sha1)
526 {
527         unsigned int h = sha1[0] << 8 | sha1[1];
528         struct object_entry *e;
529         for (e = object_table[h]; e; e = e->next)
530                 if (!hashcmp(sha1, e->sha1))
531                         return e;
532         return NULL;
533 }
534
535 static struct object_entry *insert_object(unsigned char *sha1)
536 {
537         unsigned int h = sha1[0] << 8 | sha1[1];
538         struct object_entry *e = object_table[h];
539         struct object_entry *p = NULL;
540
541         while (e) {
542                 if (!hashcmp(sha1, e->sha1))
543                         return e;
544                 p = e;
545                 e = e->next;
546         }
547
548         e = new_object(sha1);
549         e->next = NULL;
550         e->offset = 0;
551         if (p)
552                 p->next = e;
553         else
554                 object_table[h] = e;
555         return e;
556 }
557
558 static unsigned int hc_str(const char *s, size_t len)
559 {
560         unsigned int r = 0;
561         while (len-- > 0)
562                 r = r * 31 + *s++;
563         return r;
564 }
565
566 static void *pool_alloc(size_t len)
567 {
568         struct mem_pool *p;
569         void *r;
570
571         /* round up to a 'uintmax_t' alignment */
572         if (len & (sizeof(uintmax_t) - 1))
573                 len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
574
575         for (p = mem_pool; p; p = p->next_pool)
576                 if ((p->end - p->next_free >= len))
577                         break;
578
579         if (!p) {
580                 if (len >= (mem_pool_alloc/2)) {
581                         total_allocd += len;
582                         return xmalloc(len);
583                 }
584                 total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
585                 p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc);
586                 p->next_pool = mem_pool;
587                 p->next_free = (char *) p->space;
588                 p->end = p->next_free + mem_pool_alloc;
589                 mem_pool = p;
590         }
591
592         r = p->next_free;
593         p->next_free += len;
594         return r;
595 }
596
597 static void *pool_calloc(size_t count, size_t size)
598 {
599         size_t len = count * size;
600         void *r = pool_alloc(len);
601         memset(r, 0, len);
602         return r;
603 }
604
605 static char *pool_strdup(const char *s)
606 {
607         char *r = pool_alloc(strlen(s) + 1);
608         strcpy(r, s);
609         return r;
610 }
611
612 static void insert_mark(uintmax_t idnum, struct object_entry *oe)
613 {
614         struct mark_set *s = marks;
615         while ((idnum >> s->shift) >= 1024) {
616                 s = pool_calloc(1, sizeof(struct mark_set));
617                 s->shift = marks->shift + 10;
618                 s->data.sets[0] = marks;
619                 marks = s;
620         }
621         while (s->shift) {
622                 uintmax_t i = idnum >> s->shift;
623                 idnum -= i << s->shift;
624                 if (!s->data.sets[i]) {
625                         s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
626                         s->data.sets[i]->shift = s->shift - 10;
627                 }
628                 s = s->data.sets[i];
629         }
630         if (!s->data.marked[idnum])
631                 marks_set_count++;
632         s->data.marked[idnum] = oe;
633 }
634
635 static struct object_entry *find_mark(uintmax_t idnum)
636 {
637         uintmax_t orig_idnum = idnum;
638         struct mark_set *s = marks;
639         struct object_entry *oe = NULL;
640         if ((idnum >> s->shift) < 1024) {
641                 while (s && s->shift) {
642                         uintmax_t i = idnum >> s->shift;
643                         idnum -= i << s->shift;
644                         s = s->data.sets[i];
645                 }
646                 if (s)
647                         oe = s->data.marked[idnum];
648         }
649         if (!oe)
650                 die("mark :%" PRIuMAX " not declared", orig_idnum);
651         return oe;
652 }
653
654 static struct atom_str *to_atom(const char *s, unsigned short len)
655 {
656         unsigned int hc = hc_str(s, len) % atom_table_sz;
657         struct atom_str *c;
658
659         for (c = atom_table[hc]; c; c = c->next_atom)
660                 if (c->str_len == len && !strncmp(s, c->str_dat, len))
661                         return c;
662
663         c = pool_alloc(sizeof(struct atom_str) + len + 1);
664         c->str_len = len;
665         strncpy(c->str_dat, s, len);
666         c->str_dat[len] = 0;
667         c->next_atom = atom_table[hc];
668         atom_table[hc] = c;
669         atom_cnt++;
670         return c;
671 }
672
673 static struct branch *lookup_branch(const char *name)
674 {
675         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
676         struct branch *b;
677
678         for (b = branch_table[hc]; b; b = b->table_next_branch)
679                 if (!strcmp(name, b->name))
680                         return b;
681         return NULL;
682 }
683
684 static struct branch *new_branch(const char *name)
685 {
686         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
687         struct branch *b = lookup_branch(name);
688
689         if (b)
690                 die("Invalid attempt to create duplicate branch: %s", name);
691         switch (check_ref_format(name)) {
692         case 0: break; /* its valid */
693         case CHECK_REF_FORMAT_ONELEVEL:
694                 break; /* valid, but too few '/', allow anyway */
695         default:
696                 die("Branch name doesn't conform to GIT standards: %s", name);
697         }
698
699         b = pool_calloc(1, sizeof(struct branch));
700         b->name = pool_strdup(name);
701         b->table_next_branch = branch_table[hc];
702         b->branch_tree.versions[0].mode = S_IFDIR;
703         b->branch_tree.versions[1].mode = S_IFDIR;
704         b->active = 0;
705         b->pack_id = MAX_PACK_ID;
706         branch_table[hc] = b;
707         branch_count++;
708         return b;
709 }
710
711 static unsigned int hc_entries(unsigned int cnt)
712 {
713         cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
714         return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
715 }
716
717 static struct tree_content *new_tree_content(unsigned int cnt)
718 {
719         struct avail_tree_content *f, *l = NULL;
720         struct tree_content *t;
721         unsigned int hc = hc_entries(cnt);
722
723         for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
724                 if (f->entry_capacity >= cnt)
725                         break;
726
727         if (f) {
728                 if (l)
729                         l->next_avail = f->next_avail;
730                 else
731                         avail_tree_table[hc] = f->next_avail;
732         } else {
733                 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
734                 f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
735                 f->entry_capacity = cnt;
736         }
737
738         t = (struct tree_content*)f;
739         t->entry_count = 0;
740         t->delta_depth = 0;
741         return t;
742 }
743
744 static void release_tree_entry(struct tree_entry *e);
745 static void release_tree_content(struct tree_content *t)
746 {
747         struct avail_tree_content *f = (struct avail_tree_content*)t;
748         unsigned int hc = hc_entries(f->entry_capacity);
749         f->next_avail = avail_tree_table[hc];
750         avail_tree_table[hc] = f;
751 }
752
753 static void release_tree_content_recursive(struct tree_content *t)
754 {
755         unsigned int i;
756         for (i = 0; i < t->entry_count; i++)
757                 release_tree_entry(t->entries[i]);
758         release_tree_content(t);
759 }
760
761 static struct tree_content *grow_tree_content(
762         struct tree_content *t,
763         int amt)
764 {
765         struct tree_content *r = new_tree_content(t->entry_count + amt);
766         r->entry_count = t->entry_count;
767         r->delta_depth = t->delta_depth;
768         memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
769         release_tree_content(t);
770         return r;
771 }
772
773 static struct tree_entry *new_tree_entry(void)
774 {
775         struct tree_entry *e;
776
777         if (!avail_tree_entry) {
778                 unsigned int n = tree_entry_alloc;
779                 total_allocd += n * sizeof(struct tree_entry);
780                 avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry));
781                 while (n-- > 1) {
782                         *((void**)e) = e + 1;
783                         e++;
784                 }
785                 *((void**)e) = NULL;
786         }
787
788         e = avail_tree_entry;
789         avail_tree_entry = *((void**)e);
790         return e;
791 }
792
793 static void release_tree_entry(struct tree_entry *e)
794 {
795         if (e->tree)
796                 release_tree_content_recursive(e->tree);
797         *((void**)e) = avail_tree_entry;
798         avail_tree_entry = e;
799 }
800
801 static struct tree_content *dup_tree_content(struct tree_content *s)
802 {
803         struct tree_content *d;
804         struct tree_entry *a, *b;
805         unsigned int i;
806
807         if (!s)
808                 return NULL;
809         d = new_tree_content(s->entry_count);
810         for (i = 0; i < s->entry_count; i++) {
811                 a = s->entries[i];
812                 b = new_tree_entry();
813                 memcpy(b, a, sizeof(*a));
814                 if (a->tree && is_null_sha1(b->versions[1].sha1))
815                         b->tree = dup_tree_content(a->tree);
816                 else
817                         b->tree = NULL;
818                 d->entries[i] = b;
819         }
820         d->entry_count = s->entry_count;
821         d->delta_depth = s->delta_depth;
822
823         return d;
824 }
825
826 static void start_packfile(void)
827 {
828         static char tmpfile[PATH_MAX];
829         struct packed_git *p;
830         struct pack_header hdr;
831         int pack_fd;
832
833         pack_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
834                               "pack/tmp_pack_XXXXXX");
835         p = xcalloc(1, sizeof(*p) + strlen(tmpfile) + 2);
836         strcpy(p->pack_name, tmpfile);
837         p->pack_fd = pack_fd;
838
839         hdr.hdr_signature = htonl(PACK_SIGNATURE);
840         hdr.hdr_version = htonl(2);
841         hdr.hdr_entries = 0;
842         write_or_die(p->pack_fd, &hdr, sizeof(hdr));
843
844         pack_data = p;
845         pack_size = sizeof(hdr);
846         object_count = 0;
847
848         all_packs = xrealloc(all_packs, sizeof(*all_packs) * (pack_id + 1));
849         all_packs[pack_id] = p;
850 }
851
852 static int oecmp (const void *a_, const void *b_)
853 {
854         struct object_entry *a = *((struct object_entry**)a_);
855         struct object_entry *b = *((struct object_entry**)b_);
856         return hashcmp(a->sha1, b->sha1);
857 }
858
859 static char *create_index(void)
860 {
861         static char tmpfile[PATH_MAX];
862         git_SHA_CTX ctx;
863         struct sha1file *f;
864         struct object_entry **idx, **c, **last, *e;
865         struct object_entry_pool *o;
866         uint32_t array[256];
867         int i, idx_fd;
868
869         /* Build the sorted table of object IDs. */
870         idx = xmalloc(object_count * sizeof(struct object_entry*));
871         c = idx;
872         for (o = blocks; o; o = o->next_pool)
873                 for (e = o->next_free; e-- != o->entries;)
874                         if (pack_id == e->pack_id)
875                                 *c++ = e;
876         last = idx + object_count;
877         if (c != last)
878                 die("internal consistency error creating the index");
879         qsort(idx, object_count, sizeof(struct object_entry*), oecmp);
880
881         /* Generate the fan-out array. */
882         c = idx;
883         for (i = 0; i < 256; i++) {
884                 struct object_entry **next = c;
885                 while (next < last) {
886                         if ((*next)->sha1[0] != i)
887                                 break;
888                         next++;
889                 }
890                 array[i] = htonl(next - idx);
891                 c = next;
892         }
893
894         idx_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
895                              "pack/tmp_idx_XXXXXX");
896         f = sha1fd(idx_fd, tmpfile);
897         sha1write(f, array, 256 * sizeof(int));
898         git_SHA1_Init(&ctx);
899         for (c = idx; c != last; c++) {
900                 uint32_t offset = htonl((*c)->offset);
901                 sha1write(f, &offset, 4);
902                 sha1write(f, (*c)->sha1, sizeof((*c)->sha1));
903                 git_SHA1_Update(&ctx, (*c)->sha1, 20);
904         }
905         sha1write(f, pack_data->sha1, sizeof(pack_data->sha1));
906         sha1close(f, NULL, CSUM_FSYNC);
907         free(idx);
908         git_SHA1_Final(pack_data->sha1, &ctx);
909         return tmpfile;
910 }
911
912 static char *keep_pack(char *curr_index_name)
913 {
914         static char name[PATH_MAX];
915         static const char *keep_msg = "fast-import";
916         int keep_fd;
917
918         keep_fd = odb_pack_keep(name, sizeof(name), pack_data->sha1);
919         if (keep_fd < 0)
920                 die_errno("cannot create keep file");
921         write_or_die(keep_fd, keep_msg, strlen(keep_msg));
922         if (close(keep_fd))
923                 die_errno("failed to write keep file");
924
925         snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
926                  get_object_directory(), sha1_to_hex(pack_data->sha1));
927         if (move_temp_to_file(pack_data->pack_name, name))
928                 die("cannot store pack file");
929
930         snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
931                  get_object_directory(), sha1_to_hex(pack_data->sha1));
932         if (move_temp_to_file(curr_index_name, name))
933                 die("cannot store index file");
934         return name;
935 }
936
937 static void unkeep_all_packs(void)
938 {
939         static char name[PATH_MAX];
940         int k;
941
942         for (k = 0; k < pack_id; k++) {
943                 struct packed_git *p = all_packs[k];
944                 snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
945                          get_object_directory(), sha1_to_hex(p->sha1));
946                 unlink_or_warn(name);
947         }
948 }
949
950 static void end_packfile(void)
951 {
952         struct packed_git *old_p = pack_data, *new_p;
953
954         clear_delta_base_cache();
955         if (object_count) {
956                 char *idx_name;
957                 int i;
958                 struct branch *b;
959                 struct tag *t;
960
961                 close_pack_windows(pack_data);
962                 fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
963                                     pack_data->pack_name, object_count,
964                                     NULL, 0);
965                 close(pack_data->pack_fd);
966                 idx_name = keep_pack(create_index());
967
968                 /* Register the packfile with core git's machinery. */
969                 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
970                 if (!new_p)
971                         die("core git rejected index %s", idx_name);
972                 all_packs[pack_id] = new_p;
973                 install_packed_git(new_p);
974
975                 /* Print the boundary */
976                 if (pack_edges) {
977                         fprintf(pack_edges, "%s:", new_p->pack_name);
978                         for (i = 0; i < branch_table_sz; i++) {
979                                 for (b = branch_table[i]; b; b = b->table_next_branch) {
980                                         if (b->pack_id == pack_id)
981                                                 fprintf(pack_edges, " %s", sha1_to_hex(b->sha1));
982                                 }
983                         }
984                         for (t = first_tag; t; t = t->next_tag) {
985                                 if (t->pack_id == pack_id)
986                                         fprintf(pack_edges, " %s", sha1_to_hex(t->sha1));
987                         }
988                         fputc('\n', pack_edges);
989                         fflush(pack_edges);
990                 }
991
992                 pack_id++;
993         }
994         else {
995                 close(old_p->pack_fd);
996                 unlink_or_warn(old_p->pack_name);
997         }
998         free(old_p);
999
1000         /* We can't carry a delta across packfiles. */
1001         strbuf_release(&last_blob.data);
1002         last_blob.offset = 0;
1003         last_blob.depth = 0;
1004 }
1005
1006 static void cycle_packfile(void)
1007 {
1008         end_packfile();
1009         start_packfile();
1010 }
1011
1012 static size_t encode_header(
1013         enum object_type type,
1014         size_t size,
1015         unsigned char *hdr)
1016 {
1017         int n = 1;
1018         unsigned char c;
1019
1020         if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
1021                 die("bad type %d", type);
1022
1023         c = (type << 4) | (size & 15);
1024         size >>= 4;
1025         while (size) {
1026                 *hdr++ = c | 0x80;
1027                 c = size & 0x7f;
1028                 size >>= 7;
1029                 n++;
1030         }
1031         *hdr = c;
1032         return n;
1033 }
1034
1035 static int store_object(
1036         enum object_type type,
1037         struct strbuf *dat,
1038         struct last_object *last,
1039         unsigned char *sha1out,
1040         uintmax_t mark)
1041 {
1042         void *out, *delta;
1043         struct object_entry *e;
1044         unsigned char hdr[96];
1045         unsigned char sha1[20];
1046         unsigned long hdrlen, deltalen;
1047         git_SHA_CTX c;
1048         z_stream s;
1049
1050         hdrlen = sprintf((char *)hdr,"%s %lu", typename(type),
1051                 (unsigned long)dat->len) + 1;
1052         git_SHA1_Init(&c);
1053         git_SHA1_Update(&c, hdr, hdrlen);
1054         git_SHA1_Update(&c, dat->buf, dat->len);
1055         git_SHA1_Final(sha1, &c);
1056         if (sha1out)
1057                 hashcpy(sha1out, sha1);
1058
1059         e = insert_object(sha1);
1060         if (mark)
1061                 insert_mark(mark, e);
1062         if (e->offset) {
1063                 duplicate_count_by_type[type]++;
1064                 return 1;
1065         } else if (find_sha1_pack(sha1, packed_git)) {
1066                 e->type = type;
1067                 e->pack_id = MAX_PACK_ID;
1068                 e->offset = 1; /* just not zero! */
1069                 duplicate_count_by_type[type]++;
1070                 return 1;
1071         }
1072
1073         if (last && last->data.buf && last->depth < max_depth) {
1074                 delta = diff_delta(last->data.buf, last->data.len,
1075                         dat->buf, dat->len,
1076                         &deltalen, 0);
1077                 if (delta && deltalen >= dat->len) {
1078                         free(delta);
1079                         delta = NULL;
1080                 }
1081         } else
1082                 delta = NULL;
1083
1084         memset(&s, 0, sizeof(s));
1085         deflateInit(&s, pack_compression_level);
1086         if (delta) {
1087                 s.next_in = delta;
1088                 s.avail_in = deltalen;
1089         } else {
1090                 s.next_in = (void *)dat->buf;
1091                 s.avail_in = dat->len;
1092         }
1093         s.avail_out = deflateBound(&s, s.avail_in);
1094         s.next_out = out = xmalloc(s.avail_out);
1095         while (deflate(&s, Z_FINISH) == Z_OK)
1096                 /* nothing */;
1097         deflateEnd(&s);
1098
1099         /* Determine if we should auto-checkpoint. */
1100         if ((pack_size + 60 + s.total_out) > max_packsize
1101                 || (pack_size + 60 + s.total_out) < pack_size) {
1102
1103                 /* This new object needs to *not* have the current pack_id. */
1104                 e->pack_id = pack_id + 1;
1105                 cycle_packfile();
1106
1107                 /* We cannot carry a delta into the new pack. */
1108                 if (delta) {
1109                         free(delta);
1110                         delta = NULL;
1111
1112                         memset(&s, 0, sizeof(s));
1113                         deflateInit(&s, pack_compression_level);
1114                         s.next_in = (void *)dat->buf;
1115                         s.avail_in = dat->len;
1116                         s.avail_out = deflateBound(&s, s.avail_in);
1117                         s.next_out = out = xrealloc(out, s.avail_out);
1118                         while (deflate(&s, Z_FINISH) == Z_OK)
1119                                 /* nothing */;
1120                         deflateEnd(&s);
1121                 }
1122         }
1123
1124         e->type = type;
1125         e->pack_id = pack_id;
1126         e->offset = pack_size;
1127         object_count++;
1128         object_count_by_type[type]++;
1129
1130         if (delta) {
1131                 unsigned long ofs = e->offset - last->offset;
1132                 unsigned pos = sizeof(hdr) - 1;
1133
1134                 delta_count_by_type[type]++;
1135                 e->depth = last->depth + 1;
1136
1137                 hdrlen = encode_header(OBJ_OFS_DELTA, deltalen, hdr);
1138                 write_or_die(pack_data->pack_fd, hdr, hdrlen);
1139                 pack_size += hdrlen;
1140
1141                 hdr[pos] = ofs & 127;
1142                 while (ofs >>= 7)
1143                         hdr[--pos] = 128 | (--ofs & 127);
1144                 write_or_die(pack_data->pack_fd, hdr + pos, sizeof(hdr) - pos);
1145                 pack_size += sizeof(hdr) - pos;
1146         } else {
1147                 e->depth = 0;
1148                 hdrlen = encode_header(type, dat->len, hdr);
1149                 write_or_die(pack_data->pack_fd, hdr, hdrlen);
1150                 pack_size += hdrlen;
1151         }
1152
1153         write_or_die(pack_data->pack_fd, out, s.total_out);
1154         pack_size += s.total_out;
1155
1156         free(out);
1157         free(delta);
1158         if (last) {
1159                 if (last->no_swap) {
1160                         last->data = *dat;
1161                 } else {
1162                         strbuf_swap(&last->data, dat);
1163                 }
1164                 last->offset = e->offset;
1165                 last->depth = e->depth;
1166         }
1167         return 0;
1168 }
1169
1170 /* All calls must be guarded by find_object() or find_mark() to
1171  * ensure the 'struct object_entry' passed was written by this
1172  * process instance.  We unpack the entry by the offset, avoiding
1173  * the need for the corresponding .idx file.  This unpacking rule
1174  * works because we only use OBJ_REF_DELTA within the packfiles
1175  * created by fast-import.
1176  *
1177  * oe must not be NULL.  Such an oe usually comes from giving
1178  * an unknown SHA-1 to find_object() or an undefined mark to
1179  * find_mark().  Callers must test for this condition and use
1180  * the standard read_sha1_file() when it happens.
1181  *
1182  * oe->pack_id must not be MAX_PACK_ID.  Such an oe is usually from
1183  * find_mark(), where the mark was reloaded from an existing marks
1184  * file and is referencing an object that this fast-import process
1185  * instance did not write out to a packfile.  Callers must test for
1186  * this condition and use read_sha1_file() instead.
1187  */
1188 static void *gfi_unpack_entry(
1189         struct object_entry *oe,
1190         unsigned long *sizep)
1191 {
1192         enum object_type type;
1193         struct packed_git *p = all_packs[oe->pack_id];
1194         if (p == pack_data && p->pack_size < (pack_size + 20)) {
1195                 /* The object is stored in the packfile we are writing to
1196                  * and we have modified it since the last time we scanned
1197                  * back to read a previously written object.  If an old
1198                  * window covered [p->pack_size, p->pack_size + 20) its
1199                  * data is stale and is not valid.  Closing all windows
1200                  * and updating the packfile length ensures we can read
1201                  * the newly written data.
1202                  */
1203                 close_pack_windows(p);
1204
1205                 /* We have to offer 20 bytes additional on the end of
1206                  * the packfile as the core unpacker code assumes the
1207                  * footer is present at the file end and must promise
1208                  * at least 20 bytes within any window it maps.  But
1209                  * we don't actually create the footer here.
1210                  */
1211                 p->pack_size = pack_size + 20;
1212         }
1213         return unpack_entry(p, oe->offset, &type, sizep);
1214 }
1215
1216 static const char *get_mode(const char *str, uint16_t *modep)
1217 {
1218         unsigned char c;
1219         uint16_t mode = 0;
1220
1221         while ((c = *str++) != ' ') {
1222                 if (c < '0' || c > '7')
1223                         return NULL;
1224                 mode = (mode << 3) + (c - '0');
1225         }
1226         *modep = mode;
1227         return str;
1228 }
1229
1230 static void load_tree(struct tree_entry *root)
1231 {
1232         unsigned char *sha1 = root->versions[1].sha1;
1233         struct object_entry *myoe;
1234         struct tree_content *t;
1235         unsigned long size;
1236         char *buf;
1237         const char *c;
1238
1239         root->tree = t = new_tree_content(8);
1240         if (is_null_sha1(sha1))
1241                 return;
1242
1243         myoe = find_object(sha1);
1244         if (myoe && myoe->pack_id != MAX_PACK_ID) {
1245                 if (myoe->type != OBJ_TREE)
1246                         die("Not a tree: %s", sha1_to_hex(sha1));
1247                 t->delta_depth = myoe->depth;
1248                 buf = gfi_unpack_entry(myoe, &size);
1249                 if (!buf)
1250                         die("Can't load tree %s", sha1_to_hex(sha1));
1251         } else {
1252                 enum object_type type;
1253                 buf = read_sha1_file(sha1, &type, &size);
1254                 if (!buf || type != OBJ_TREE)
1255                         die("Can't load tree %s", sha1_to_hex(sha1));
1256         }
1257
1258         c = buf;
1259         while (c != (buf + size)) {
1260                 struct tree_entry *e = new_tree_entry();
1261
1262                 if (t->entry_count == t->entry_capacity)
1263                         root->tree = t = grow_tree_content(t, t->entry_count);
1264                 t->entries[t->entry_count++] = e;
1265
1266                 e->tree = NULL;
1267                 c = get_mode(c, &e->versions[1].mode);
1268                 if (!c)
1269                         die("Corrupt mode in %s", sha1_to_hex(sha1));
1270                 e->versions[0].mode = e->versions[1].mode;
1271                 e->name = to_atom(c, strlen(c));
1272                 c += e->name->str_len + 1;
1273                 hashcpy(e->versions[0].sha1, (unsigned char *)c);
1274                 hashcpy(e->versions[1].sha1, (unsigned char *)c);
1275                 c += 20;
1276         }
1277         free(buf);
1278 }
1279
1280 static int tecmp0 (const void *_a, const void *_b)
1281 {
1282         struct tree_entry *a = *((struct tree_entry**)_a);
1283         struct tree_entry *b = *((struct tree_entry**)_b);
1284         return base_name_compare(
1285                 a->name->str_dat, a->name->str_len, a->versions[0].mode,
1286                 b->name->str_dat, b->name->str_len, b->versions[0].mode);
1287 }
1288
1289 static int tecmp1 (const void *_a, const void *_b)
1290 {
1291         struct tree_entry *a = *((struct tree_entry**)_a);
1292         struct tree_entry *b = *((struct tree_entry**)_b);
1293         return base_name_compare(
1294                 a->name->str_dat, a->name->str_len, a->versions[1].mode,
1295                 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1296 }
1297
1298 static void mktree(struct tree_content *t, int v, struct strbuf *b)
1299 {
1300         size_t maxlen = 0;
1301         unsigned int i;
1302
1303         if (!v)
1304                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0);
1305         else
1306                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1);
1307
1308         for (i = 0; i < t->entry_count; i++) {
1309                 if (t->entries[i]->versions[v].mode)
1310                         maxlen += t->entries[i]->name->str_len + 34;
1311         }
1312
1313         strbuf_reset(b);
1314         strbuf_grow(b, maxlen);
1315         for (i = 0; i < t->entry_count; i++) {
1316                 struct tree_entry *e = t->entries[i];
1317                 if (!e->versions[v].mode)
1318                         continue;
1319                 strbuf_addf(b, "%o %s%c", (unsigned int)e->versions[v].mode,
1320                                         e->name->str_dat, '\0');
1321                 strbuf_add(b, e->versions[v].sha1, 20);
1322         }
1323 }
1324
1325 static void store_tree(struct tree_entry *root)
1326 {
1327         struct tree_content *t = root->tree;
1328         unsigned int i, j, del;
1329         struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1330         struct object_entry *le;
1331
1332         if (!is_null_sha1(root->versions[1].sha1))
1333                 return;
1334
1335         for (i = 0; i < t->entry_count; i++) {
1336                 if (t->entries[i]->tree)
1337                         store_tree(t->entries[i]);
1338         }
1339
1340         le = find_object(root->versions[0].sha1);
1341         if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1342                 mktree(t, 0, &old_tree);
1343                 lo.data = old_tree;
1344                 lo.offset = le->offset;
1345                 lo.depth = t->delta_depth;
1346         }
1347
1348         mktree(t, 1, &new_tree);
1349         store_object(OBJ_TREE, &new_tree, &lo, root->versions[1].sha1, 0);
1350
1351         t->delta_depth = lo.depth;
1352         for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1353                 struct tree_entry *e = t->entries[i];
1354                 if (e->versions[1].mode) {
1355                         e->versions[0].mode = e->versions[1].mode;
1356                         hashcpy(e->versions[0].sha1, e->versions[1].sha1);
1357                         t->entries[j++] = e;
1358                 } else {
1359                         release_tree_entry(e);
1360                         del++;
1361                 }
1362         }
1363         t->entry_count -= del;
1364 }
1365
1366 static int tree_content_set(
1367         struct tree_entry *root,
1368         const char *p,
1369         const unsigned char *sha1,
1370         const uint16_t mode,
1371         struct tree_content *subtree)
1372 {
1373         struct tree_content *t = root->tree;
1374         const char *slash1;
1375         unsigned int i, n;
1376         struct tree_entry *e;
1377
1378         slash1 = strchr(p, '/');
1379         if (slash1)
1380                 n = slash1 - p;
1381         else
1382                 n = strlen(p);
1383         if (!n)
1384                 die("Empty path component found in input");
1385         if (!slash1 && !S_ISDIR(mode) && subtree)
1386                 die("Non-directories cannot have subtrees");
1387
1388         for (i = 0; i < t->entry_count; i++) {
1389                 e = t->entries[i];
1390                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1391                         if (!slash1) {
1392                                 if (!S_ISDIR(mode)
1393                                                 && e->versions[1].mode == mode
1394                                                 && !hashcmp(e->versions[1].sha1, sha1))
1395                                         return 0;
1396                                 e->versions[1].mode = mode;
1397                                 hashcpy(e->versions[1].sha1, sha1);
1398                                 if (e->tree)
1399                                         release_tree_content_recursive(e->tree);
1400                                 e->tree = subtree;
1401                                 hashclr(root->versions[1].sha1);
1402                                 return 1;
1403                         }
1404                         if (!S_ISDIR(e->versions[1].mode)) {
1405                                 e->tree = new_tree_content(8);
1406                                 e->versions[1].mode = S_IFDIR;
1407                         }
1408                         if (!e->tree)
1409                                 load_tree(e);
1410                         if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) {
1411                                 hashclr(root->versions[1].sha1);
1412                                 return 1;
1413                         }
1414                         return 0;
1415                 }
1416         }
1417
1418         if (t->entry_count == t->entry_capacity)
1419                 root->tree = t = grow_tree_content(t, t->entry_count);
1420         e = new_tree_entry();
1421         e->name = to_atom(p, n);
1422         e->versions[0].mode = 0;
1423         hashclr(e->versions[0].sha1);
1424         t->entries[t->entry_count++] = e;
1425         if (slash1) {
1426                 e->tree = new_tree_content(8);
1427                 e->versions[1].mode = S_IFDIR;
1428                 tree_content_set(e, slash1 + 1, sha1, mode, subtree);
1429         } else {
1430                 e->tree = subtree;
1431                 e->versions[1].mode = mode;
1432                 hashcpy(e->versions[1].sha1, sha1);
1433         }
1434         hashclr(root->versions[1].sha1);
1435         return 1;
1436 }
1437
1438 static int tree_content_remove(
1439         struct tree_entry *root,
1440         const char *p,
1441         struct tree_entry *backup_leaf)
1442 {
1443         struct tree_content *t = root->tree;
1444         const char *slash1;
1445         unsigned int i, n;
1446         struct tree_entry *e;
1447
1448         slash1 = strchr(p, '/');
1449         if (slash1)
1450                 n = slash1 - p;
1451         else
1452                 n = strlen(p);
1453
1454         for (i = 0; i < t->entry_count; i++) {
1455                 e = t->entries[i];
1456                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1457                         if (!slash1 || !S_ISDIR(e->versions[1].mode))
1458                                 goto del_entry;
1459                         if (!e->tree)
1460                                 load_tree(e);
1461                         if (tree_content_remove(e, slash1 + 1, backup_leaf)) {
1462                                 for (n = 0; n < e->tree->entry_count; n++) {
1463                                         if (e->tree->entries[n]->versions[1].mode) {
1464                                                 hashclr(root->versions[1].sha1);
1465                                                 return 1;
1466                                         }
1467                                 }
1468                                 backup_leaf = NULL;
1469                                 goto del_entry;
1470                         }
1471                         return 0;
1472                 }
1473         }
1474         return 0;
1475
1476 del_entry:
1477         if (backup_leaf)
1478                 memcpy(backup_leaf, e, sizeof(*backup_leaf));
1479         else if (e->tree)
1480                 release_tree_content_recursive(e->tree);
1481         e->tree = NULL;
1482         e->versions[1].mode = 0;
1483         hashclr(e->versions[1].sha1);
1484         hashclr(root->versions[1].sha1);
1485         return 1;
1486 }
1487
1488 static int tree_content_get(
1489         struct tree_entry *root,
1490         const char *p,
1491         struct tree_entry *leaf)
1492 {
1493         struct tree_content *t = root->tree;
1494         const char *slash1;
1495         unsigned int i, n;
1496         struct tree_entry *e;
1497
1498         slash1 = strchr(p, '/');
1499         if (slash1)
1500                 n = slash1 - p;
1501         else
1502                 n = strlen(p);
1503
1504         for (i = 0; i < t->entry_count; i++) {
1505                 e = t->entries[i];
1506                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1507                         if (!slash1) {
1508                                 memcpy(leaf, e, sizeof(*leaf));
1509                                 if (e->tree && is_null_sha1(e->versions[1].sha1))
1510                                         leaf->tree = dup_tree_content(e->tree);
1511                                 else
1512                                         leaf->tree = NULL;
1513                                 return 1;
1514                         }
1515                         if (!S_ISDIR(e->versions[1].mode))
1516                                 return 0;
1517                         if (!e->tree)
1518                                 load_tree(e);
1519                         return tree_content_get(e, slash1 + 1, leaf);
1520                 }
1521         }
1522         return 0;
1523 }
1524
1525 static int update_branch(struct branch *b)
1526 {
1527         static const char *msg = "fast-import";
1528         struct ref_lock *lock;
1529         unsigned char old_sha1[20];
1530
1531         if (is_null_sha1(b->sha1))
1532                 return 0;
1533         if (read_ref(b->name, old_sha1))
1534                 hashclr(old_sha1);
1535         lock = lock_any_ref_for_update(b->name, old_sha1, 0);
1536         if (!lock)
1537                 return error("Unable to lock %s", b->name);
1538         if (!force_update && !is_null_sha1(old_sha1)) {
1539                 struct commit *old_cmit, *new_cmit;
1540
1541                 old_cmit = lookup_commit_reference_gently(old_sha1, 0);
1542                 new_cmit = lookup_commit_reference_gently(b->sha1, 0);
1543                 if (!old_cmit || !new_cmit) {
1544                         unlock_ref(lock);
1545                         return error("Branch %s is missing commits.", b->name);
1546                 }
1547
1548                 if (!in_merge_bases(old_cmit, &new_cmit, 1)) {
1549                         unlock_ref(lock);
1550                         warning("Not updating %s"
1551                                 " (new tip %s does not contain %s)",
1552                                 b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1));
1553                         return -1;
1554                 }
1555         }
1556         if (write_ref_sha1(lock, b->sha1, msg) < 0)
1557                 return error("Unable to update %s", b->name);
1558         return 0;
1559 }
1560
1561 static void dump_branches(void)
1562 {
1563         unsigned int i;
1564         struct branch *b;
1565
1566         for (i = 0; i < branch_table_sz; i++) {
1567                 for (b = branch_table[i]; b; b = b->table_next_branch)
1568                         failure |= update_branch(b);
1569         }
1570 }
1571
1572 static void dump_tags(void)
1573 {
1574         static const char *msg = "fast-import";
1575         struct tag *t;
1576         struct ref_lock *lock;
1577         char ref_name[PATH_MAX];
1578
1579         for (t = first_tag; t; t = t->next_tag) {
1580                 sprintf(ref_name, "tags/%s", t->name);
1581                 lock = lock_ref_sha1(ref_name, NULL);
1582                 if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
1583                         failure |= error("Unable to update %s", ref_name);
1584         }
1585 }
1586
1587 static void dump_marks_helper(FILE *f,
1588         uintmax_t base,
1589         struct mark_set *m)
1590 {
1591         uintmax_t k;
1592         if (m->shift) {
1593                 for (k = 0; k < 1024; k++) {
1594                         if (m->data.sets[k])
1595                                 dump_marks_helper(f, (base + k) << m->shift,
1596                                         m->data.sets[k]);
1597                 }
1598         } else {
1599                 for (k = 0; k < 1024; k++) {
1600                         if (m->data.marked[k])
1601                                 fprintf(f, ":%" PRIuMAX " %s\n", base + k,
1602                                         sha1_to_hex(m->data.marked[k]->sha1));
1603                 }
1604         }
1605 }
1606
1607 static void dump_marks(void)
1608 {
1609         static struct lock_file mark_lock;
1610         int mark_fd;
1611         FILE *f;
1612
1613         if (!export_marks_file)
1614                 return;
1615
1616         mark_fd = hold_lock_file_for_update(&mark_lock, export_marks_file, 0);
1617         if (mark_fd < 0) {
1618                 failure |= error("Unable to write marks file %s: %s",
1619                         export_marks_file, strerror(errno));
1620                 return;
1621         }
1622
1623         f = fdopen(mark_fd, "w");
1624         if (!f) {
1625                 int saved_errno = errno;
1626                 rollback_lock_file(&mark_lock);
1627                 failure |= error("Unable to write marks file %s: %s",
1628                         export_marks_file, strerror(saved_errno));
1629                 return;
1630         }
1631
1632         /*
1633          * Since the lock file was fdopen()'ed, it should not be close()'ed.
1634          * Assign -1 to the lock file descriptor so that commit_lock_file()
1635          * won't try to close() it.
1636          */
1637         mark_lock.fd = -1;
1638
1639         dump_marks_helper(f, 0, marks);
1640         if (ferror(f) || fclose(f)) {
1641                 int saved_errno = errno;
1642                 rollback_lock_file(&mark_lock);
1643                 failure |= error("Unable to write marks file %s: %s",
1644                         export_marks_file, strerror(saved_errno));
1645                 return;
1646         }
1647
1648         if (commit_lock_file(&mark_lock)) {
1649                 int saved_errno = errno;
1650                 rollback_lock_file(&mark_lock);
1651                 failure |= error("Unable to commit marks file %s: %s",
1652                         export_marks_file, strerror(saved_errno));
1653                 return;
1654         }
1655 }
1656
1657 static void read_marks(void)
1658 {
1659         char line[512];
1660         FILE *f = fopen(import_marks_file, "r");
1661         if (!f)
1662                 die_errno("cannot read '%s'", import_marks_file);
1663         while (fgets(line, sizeof(line), f)) {
1664                 uintmax_t mark;
1665                 char *end;
1666                 unsigned char sha1[20];
1667                 struct object_entry *e;
1668
1669                 end = strchr(line, '\n');
1670                 if (line[0] != ':' || !end)
1671                         die("corrupt mark line: %s", line);
1672                 *end = 0;
1673                 mark = strtoumax(line + 1, &end, 10);
1674                 if (!mark || end == line + 1
1675                         || *end != ' ' || get_sha1(end + 1, sha1))
1676                         die("corrupt mark line: %s", line);
1677                 e = find_object(sha1);
1678                 if (!e) {
1679                         enum object_type type = sha1_object_info(sha1, NULL);
1680                         if (type < 0)
1681                                 die("object not found: %s", sha1_to_hex(sha1));
1682                         e = insert_object(sha1);
1683                         e->type = type;
1684                         e->pack_id = MAX_PACK_ID;
1685                         e->offset = 1; /* just not zero! */
1686                 }
1687                 insert_mark(mark, e);
1688         }
1689         fclose(f);
1690 }
1691
1692
1693 static int read_next_command(void)
1694 {
1695         static int stdin_eof = 0;
1696
1697         if (stdin_eof) {
1698                 unread_command_buf = 0;
1699                 return EOF;
1700         }
1701
1702         do {
1703                 if (unread_command_buf) {
1704                         unread_command_buf = 0;
1705                 } else {
1706                         struct recent_command *rc;
1707
1708                         strbuf_detach(&command_buf, NULL);
1709                         stdin_eof = strbuf_getline(&command_buf, stdin, '\n');
1710                         if (stdin_eof)
1711                                 return EOF;
1712
1713                         if (!seen_data_command
1714                                 && prefixcmp(command_buf.buf, "feature ")
1715                                 && prefixcmp(command_buf.buf, "option ")) {
1716                                 parse_argv();
1717                         }
1718
1719                         rc = rc_free;
1720                         if (rc)
1721                                 rc_free = rc->next;
1722                         else {
1723                                 rc = cmd_hist.next;
1724                                 cmd_hist.next = rc->next;
1725                                 cmd_hist.next->prev = &cmd_hist;
1726                                 free(rc->buf);
1727                         }
1728
1729                         rc->buf = command_buf.buf;
1730                         rc->prev = cmd_tail;
1731                         rc->next = cmd_hist.prev;
1732                         rc->prev->next = rc;
1733                         cmd_tail = rc;
1734                 }
1735         } while (command_buf.buf[0] == '#');
1736
1737         return 0;
1738 }
1739
1740 static void skip_optional_lf(void)
1741 {
1742         int term_char = fgetc(stdin);
1743         if (term_char != '\n' && term_char != EOF)
1744                 ungetc(term_char, stdin);
1745 }
1746
1747 static void parse_mark(void)
1748 {
1749         if (!prefixcmp(command_buf.buf, "mark :")) {
1750                 next_mark = strtoumax(command_buf.buf + 6, NULL, 10);
1751                 read_next_command();
1752         }
1753         else
1754                 next_mark = 0;
1755 }
1756
1757 static void parse_data(struct strbuf *sb)
1758 {
1759         strbuf_reset(sb);
1760
1761         if (prefixcmp(command_buf.buf, "data "))
1762                 die("Expected 'data n' command, found: %s", command_buf.buf);
1763
1764         if (!prefixcmp(command_buf.buf + 5, "<<")) {
1765                 char *term = xstrdup(command_buf.buf + 5 + 2);
1766                 size_t term_len = command_buf.len - 5 - 2;
1767
1768                 strbuf_detach(&command_buf, NULL);
1769                 for (;;) {
1770                         if (strbuf_getline(&command_buf, stdin, '\n') == EOF)
1771                                 die("EOF in data (terminator '%s' not found)", term);
1772                         if (term_len == command_buf.len
1773                                 && !strcmp(term, command_buf.buf))
1774                                 break;
1775                         strbuf_addbuf(sb, &command_buf);
1776                         strbuf_addch(sb, '\n');
1777                 }
1778                 free(term);
1779         }
1780         else {
1781                 size_t n = 0, length;
1782
1783                 length = strtoul(command_buf.buf + 5, NULL, 10);
1784
1785                 while (n < length) {
1786                         size_t s = strbuf_fread(sb, length - n, stdin);
1787                         if (!s && feof(stdin))
1788                                 die("EOF in data (%lu bytes remaining)",
1789                                         (unsigned long)(length - n));
1790                         n += s;
1791                 }
1792         }
1793
1794         skip_optional_lf();
1795 }
1796
1797 static int validate_raw_date(const char *src, char *result, int maxlen)
1798 {
1799         const char *orig_src = src;
1800         char *endp;
1801         unsigned long num;
1802
1803         errno = 0;
1804
1805         num = strtoul(src, &endp, 10);
1806         /* NEEDSWORK: perhaps check for reasonable values? */
1807         if (errno || endp == src || *endp != ' ')
1808                 return -1;
1809
1810         src = endp + 1;
1811         if (*src != '-' && *src != '+')
1812                 return -1;
1813
1814         num = strtoul(src + 1, &endp, 10);
1815         if (errno || endp == src + 1 || *endp || (endp - orig_src) >= maxlen ||
1816             1400 < num)
1817                 return -1;
1818
1819         strcpy(result, orig_src);
1820         return 0;
1821 }
1822
1823 static char *parse_ident(const char *buf)
1824 {
1825         const char *gt;
1826         size_t name_len;
1827         char *ident;
1828
1829         gt = strrchr(buf, '>');
1830         if (!gt)
1831                 die("Missing > in ident string: %s", buf);
1832         gt++;
1833         if (*gt != ' ')
1834                 die("Missing space after > in ident string: %s", buf);
1835         gt++;
1836         name_len = gt - buf;
1837         ident = xmalloc(name_len + 24);
1838         strncpy(ident, buf, name_len);
1839
1840         switch (whenspec) {
1841         case WHENSPEC_RAW:
1842                 if (validate_raw_date(gt, ident + name_len, 24) < 0)
1843                         die("Invalid raw date \"%s\" in ident: %s", gt, buf);
1844                 break;
1845         case WHENSPEC_RFC2822:
1846                 if (parse_date(gt, ident + name_len, 24) < 0)
1847                         die("Invalid rfc2822 date \"%s\" in ident: %s", gt, buf);
1848                 break;
1849         case WHENSPEC_NOW:
1850                 if (strcmp("now", gt))
1851                         die("Date in ident must be 'now': %s", buf);
1852                 datestamp(ident + name_len, 24);
1853                 break;
1854         }
1855
1856         return ident;
1857 }
1858
1859 static void parse_new_blob(void)
1860 {
1861         static struct strbuf buf = STRBUF_INIT;
1862
1863         read_next_command();
1864         parse_mark();
1865         parse_data(&buf);
1866         store_object(OBJ_BLOB, &buf, &last_blob, NULL, next_mark);
1867 }
1868
1869 static void unload_one_branch(void)
1870 {
1871         while (cur_active_branches
1872                 && cur_active_branches >= max_active_branches) {
1873                 uintmax_t min_commit = ULONG_MAX;
1874                 struct branch *e, *l = NULL, *p = NULL;
1875
1876                 for (e = active_branches; e; e = e->active_next_branch) {
1877                         if (e->last_commit < min_commit) {
1878                                 p = l;
1879                                 min_commit = e->last_commit;
1880                         }
1881                         l = e;
1882                 }
1883
1884                 if (p) {
1885                         e = p->active_next_branch;
1886                         p->active_next_branch = e->active_next_branch;
1887                 } else {
1888                         e = active_branches;
1889                         active_branches = e->active_next_branch;
1890                 }
1891                 e->active = 0;
1892                 e->active_next_branch = NULL;
1893                 if (e->branch_tree.tree) {
1894                         release_tree_content_recursive(e->branch_tree.tree);
1895                         e->branch_tree.tree = NULL;
1896                 }
1897                 cur_active_branches--;
1898         }
1899 }
1900
1901 static void load_branch(struct branch *b)
1902 {
1903         load_tree(&b->branch_tree);
1904         if (!b->active) {
1905                 b->active = 1;
1906                 b->active_next_branch = active_branches;
1907                 active_branches = b;
1908                 cur_active_branches++;
1909                 branch_load_count++;
1910         }
1911 }
1912
1913 static void file_change_m(struct branch *b)
1914 {
1915         const char *p = command_buf.buf + 2;
1916         static struct strbuf uq = STRBUF_INIT;
1917         const char *endp;
1918         struct object_entry *oe = oe;
1919         unsigned char sha1[20];
1920         uint16_t mode, inline_data = 0;
1921
1922         p = get_mode(p, &mode);
1923         if (!p)
1924                 die("Corrupt mode: %s", command_buf.buf);
1925         switch (mode) {
1926         case 0644:
1927         case 0755:
1928                 mode |= S_IFREG;
1929         case S_IFREG | 0644:
1930         case S_IFREG | 0755:
1931         case S_IFLNK:
1932         case S_IFGITLINK:
1933                 /* ok */
1934                 break;
1935         default:
1936                 die("Corrupt mode: %s", command_buf.buf);
1937         }
1938
1939         if (*p == ':') {
1940                 char *x;
1941                 oe = find_mark(strtoumax(p + 1, &x, 10));
1942                 hashcpy(sha1, oe->sha1);
1943                 p = x;
1944         } else if (!prefixcmp(p, "inline")) {
1945                 inline_data = 1;
1946                 p += 6;
1947         } else {
1948                 if (get_sha1_hex(p, sha1))
1949                         die("Invalid SHA1: %s", command_buf.buf);
1950                 oe = find_object(sha1);
1951                 p += 40;
1952         }
1953         if (*p++ != ' ')
1954                 die("Missing space after SHA1: %s", command_buf.buf);
1955
1956         strbuf_reset(&uq);
1957         if (!unquote_c_style(&uq, p, &endp)) {
1958                 if (*endp)
1959                         die("Garbage after path in: %s", command_buf.buf);
1960                 p = uq.buf;
1961         }
1962
1963         if (S_ISGITLINK(mode)) {
1964                 if (inline_data)
1965                         die("Git links cannot be specified 'inline': %s",
1966                                 command_buf.buf);
1967                 else if (oe) {
1968                         if (oe->type != OBJ_COMMIT)
1969                                 die("Not a commit (actually a %s): %s",
1970                                         typename(oe->type), command_buf.buf);
1971                 }
1972                 /*
1973                  * Accept the sha1 without checking; it expected to be in
1974                  * another repository.
1975                  */
1976         } else if (inline_data) {
1977                 static struct strbuf buf = STRBUF_INIT;
1978
1979                 if (p != uq.buf) {
1980                         strbuf_addstr(&uq, p);
1981                         p = uq.buf;
1982                 }
1983                 read_next_command();
1984                 parse_data(&buf);
1985                 store_object(OBJ_BLOB, &buf, &last_blob, sha1, 0);
1986         } else if (oe) {
1987                 if (oe->type != OBJ_BLOB)
1988                         die("Not a blob (actually a %s): %s",
1989                                 typename(oe->type), command_buf.buf);
1990         } else {
1991                 enum object_type type = sha1_object_info(sha1, NULL);
1992                 if (type < 0)
1993                         die("Blob not found: %s", command_buf.buf);
1994                 if (type != OBJ_BLOB)
1995                         die("Not a blob (actually a %s): %s",
1996                             typename(type), command_buf.buf);
1997         }
1998
1999         tree_content_set(&b->branch_tree, p, sha1, mode, NULL);
2000 }
2001
2002 static void file_change_d(struct branch *b)
2003 {
2004         const char *p = command_buf.buf + 2;
2005         static struct strbuf uq = STRBUF_INIT;
2006         const char *endp;
2007
2008         strbuf_reset(&uq);
2009         if (!unquote_c_style(&uq, p, &endp)) {
2010                 if (*endp)
2011                         die("Garbage after path in: %s", command_buf.buf);
2012                 p = uq.buf;
2013         }
2014         tree_content_remove(&b->branch_tree, p, NULL);
2015 }
2016
2017 static void file_change_cr(struct branch *b, int rename)
2018 {
2019         const char *s, *d;
2020         static struct strbuf s_uq = STRBUF_INIT;
2021         static struct strbuf d_uq = STRBUF_INIT;
2022         const char *endp;
2023         struct tree_entry leaf;
2024
2025         s = command_buf.buf + 2;
2026         strbuf_reset(&s_uq);
2027         if (!unquote_c_style(&s_uq, s, &endp)) {
2028                 if (*endp != ' ')
2029                         die("Missing space after source: %s", command_buf.buf);
2030         } else {
2031                 endp = strchr(s, ' ');
2032                 if (!endp)
2033                         die("Missing space after source: %s", command_buf.buf);
2034                 strbuf_add(&s_uq, s, endp - s);
2035         }
2036         s = s_uq.buf;
2037
2038         endp++;
2039         if (!*endp)
2040                 die("Missing dest: %s", command_buf.buf);
2041
2042         d = endp;
2043         strbuf_reset(&d_uq);
2044         if (!unquote_c_style(&d_uq, d, &endp)) {
2045                 if (*endp)
2046                         die("Garbage after dest in: %s", command_buf.buf);
2047                 d = d_uq.buf;
2048         }
2049
2050         memset(&leaf, 0, sizeof(leaf));
2051         if (rename)
2052                 tree_content_remove(&b->branch_tree, s, &leaf);
2053         else
2054                 tree_content_get(&b->branch_tree, s, &leaf);
2055         if (!leaf.versions[1].mode)
2056                 die("Path %s not in branch", s);
2057         tree_content_set(&b->branch_tree, d,
2058                 leaf.versions[1].sha1,
2059                 leaf.versions[1].mode,
2060                 leaf.tree);
2061 }
2062
2063 static void note_change_n(struct branch *b)
2064 {
2065         const char *p = command_buf.buf + 2;
2066         static struct strbuf uq = STRBUF_INIT;
2067         struct object_entry *oe = oe;
2068         struct branch *s;
2069         unsigned char sha1[20], commit_sha1[20];
2070         uint16_t inline_data = 0;
2071
2072         /* <dataref> or 'inline' */
2073         if (*p == ':') {
2074                 char *x;
2075                 oe = find_mark(strtoumax(p + 1, &x, 10));
2076                 hashcpy(sha1, oe->sha1);
2077                 p = x;
2078         } else if (!prefixcmp(p, "inline")) {
2079                 inline_data = 1;
2080                 p += 6;
2081         } else {
2082                 if (get_sha1_hex(p, sha1))
2083                         die("Invalid SHA1: %s", command_buf.buf);
2084                 oe = find_object(sha1);
2085                 p += 40;
2086         }
2087         if (*p++ != ' ')
2088                 die("Missing space after SHA1: %s", command_buf.buf);
2089
2090         /* <committish> */
2091         s = lookup_branch(p);
2092         if (s) {
2093                 hashcpy(commit_sha1, s->sha1);
2094         } else if (*p == ':') {
2095                 uintmax_t commit_mark = strtoumax(p + 1, NULL, 10);
2096                 struct object_entry *commit_oe = find_mark(commit_mark);
2097                 if (commit_oe->type != OBJ_COMMIT)
2098                         die("Mark :%" PRIuMAX " not a commit", commit_mark);
2099                 hashcpy(commit_sha1, commit_oe->sha1);
2100         } else if (!get_sha1(p, commit_sha1)) {
2101                 unsigned long size;
2102                 char *buf = read_object_with_reference(commit_sha1,
2103                         commit_type, &size, commit_sha1);
2104                 if (!buf || size < 46)
2105                         die("Not a valid commit: %s", p);
2106                 free(buf);
2107         } else
2108                 die("Invalid ref name or SHA1 expression: %s", p);
2109
2110         if (inline_data) {
2111                 static struct strbuf buf = STRBUF_INIT;
2112
2113                 if (p != uq.buf) {
2114                         strbuf_addstr(&uq, p);
2115                         p = uq.buf;
2116                 }
2117                 read_next_command();
2118                 parse_data(&buf);
2119                 store_object(OBJ_BLOB, &buf, &last_blob, sha1, 0);
2120         } else if (oe) {
2121                 if (oe->type != OBJ_BLOB)
2122                         die("Not a blob (actually a %s): %s",
2123                                 typename(oe->type), command_buf.buf);
2124         } else {
2125                 enum object_type type = sha1_object_info(sha1, NULL);
2126                 if (type < 0)
2127                         die("Blob not found: %s", command_buf.buf);
2128                 if (type != OBJ_BLOB)
2129                         die("Not a blob (actually a %s): %s",
2130                             typename(type), command_buf.buf);
2131         }
2132
2133         tree_content_set(&b->branch_tree, sha1_to_hex(commit_sha1), sha1,
2134                 S_IFREG | 0644, NULL);
2135 }
2136
2137 static void file_change_deleteall(struct branch *b)
2138 {
2139         release_tree_content_recursive(b->branch_tree.tree);
2140         hashclr(b->branch_tree.versions[0].sha1);
2141         hashclr(b->branch_tree.versions[1].sha1);
2142         load_tree(&b->branch_tree);
2143 }
2144
2145 static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2146 {
2147         if (!buf || size < 46)
2148                 die("Not a valid commit: %s", sha1_to_hex(b->sha1));
2149         if (memcmp("tree ", buf, 5)
2150                 || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
2151                 die("The commit %s is corrupt", sha1_to_hex(b->sha1));
2152         hashcpy(b->branch_tree.versions[0].sha1,
2153                 b->branch_tree.versions[1].sha1);
2154 }
2155
2156 static void parse_from_existing(struct branch *b)
2157 {
2158         if (is_null_sha1(b->sha1)) {
2159                 hashclr(b->branch_tree.versions[0].sha1);
2160                 hashclr(b->branch_tree.versions[1].sha1);
2161         } else {
2162                 unsigned long size;
2163                 char *buf;
2164
2165                 buf = read_object_with_reference(b->sha1,
2166                         commit_type, &size, b->sha1);
2167                 parse_from_commit(b, buf, size);
2168                 free(buf);
2169         }
2170 }
2171
2172 static int parse_from(struct branch *b)
2173 {
2174         const char *from;
2175         struct branch *s;
2176
2177         if (prefixcmp(command_buf.buf, "from "))
2178                 return 0;
2179
2180         if (b->branch_tree.tree) {
2181                 release_tree_content_recursive(b->branch_tree.tree);
2182                 b->branch_tree.tree = NULL;
2183         }
2184
2185         from = strchr(command_buf.buf, ' ') + 1;
2186         s = lookup_branch(from);
2187         if (b == s)
2188                 die("Can't create a branch from itself: %s", b->name);
2189         else if (s) {
2190                 unsigned char *t = s->branch_tree.versions[1].sha1;
2191                 hashcpy(b->sha1, s->sha1);
2192                 hashcpy(b->branch_tree.versions[0].sha1, t);
2193                 hashcpy(b->branch_tree.versions[1].sha1, t);
2194         } else if (*from == ':') {
2195                 uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2196                 struct object_entry *oe = find_mark(idnum);
2197                 if (oe->type != OBJ_COMMIT)
2198                         die("Mark :%" PRIuMAX " not a commit", idnum);
2199                 hashcpy(b->sha1, oe->sha1);
2200                 if (oe->pack_id != MAX_PACK_ID) {
2201                         unsigned long size;
2202                         char *buf = gfi_unpack_entry(oe, &size);
2203                         parse_from_commit(b, buf, size);
2204                         free(buf);
2205                 } else
2206                         parse_from_existing(b);
2207         } else if (!get_sha1(from, b->sha1))
2208                 parse_from_existing(b);
2209         else
2210                 die("Invalid ref name or SHA1 expression: %s", from);
2211
2212         read_next_command();
2213         return 1;
2214 }
2215
2216 static struct hash_list *parse_merge(unsigned int *count)
2217 {
2218         struct hash_list *list = NULL, *n, *e = e;
2219         const char *from;
2220         struct branch *s;
2221
2222         *count = 0;
2223         while (!prefixcmp(command_buf.buf, "merge ")) {
2224                 from = strchr(command_buf.buf, ' ') + 1;
2225                 n = xmalloc(sizeof(*n));
2226                 s = lookup_branch(from);
2227                 if (s)
2228                         hashcpy(n->sha1, s->sha1);
2229                 else if (*from == ':') {
2230                         uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2231                         struct object_entry *oe = find_mark(idnum);
2232                         if (oe->type != OBJ_COMMIT)
2233                                 die("Mark :%" PRIuMAX " not a commit", idnum);
2234                         hashcpy(n->sha1, oe->sha1);
2235                 } else if (!get_sha1(from, n->sha1)) {
2236                         unsigned long size;
2237                         char *buf = read_object_with_reference(n->sha1,
2238                                 commit_type, &size, n->sha1);
2239                         if (!buf || size < 46)
2240                                 die("Not a valid commit: %s", from);
2241                         free(buf);
2242                 } else
2243                         die("Invalid ref name or SHA1 expression: %s", from);
2244
2245                 n->next = NULL;
2246                 if (list)
2247                         e->next = n;
2248                 else
2249                         list = n;
2250                 e = n;
2251                 (*count)++;
2252                 read_next_command();
2253         }
2254         return list;
2255 }
2256
2257 static void parse_new_commit(void)
2258 {
2259         static struct strbuf msg = STRBUF_INIT;
2260         struct branch *b;
2261         char *sp;
2262         char *author = NULL;
2263         char *committer = NULL;
2264         struct hash_list *merge_list = NULL;
2265         unsigned int merge_count;
2266
2267         /* Obtain the branch name from the rest of our command */
2268         sp = strchr(command_buf.buf, ' ') + 1;
2269         b = lookup_branch(sp);
2270         if (!b)
2271                 b = new_branch(sp);
2272
2273         read_next_command();
2274         parse_mark();
2275         if (!prefixcmp(command_buf.buf, "author ")) {
2276                 author = parse_ident(command_buf.buf + 7);
2277                 read_next_command();
2278         }
2279         if (!prefixcmp(command_buf.buf, "committer ")) {
2280                 committer = parse_ident(command_buf.buf + 10);
2281                 read_next_command();
2282         }
2283         if (!committer)
2284                 die("Expected committer but didn't get one");
2285         parse_data(&msg);
2286         read_next_command();
2287         parse_from(b);
2288         merge_list = parse_merge(&merge_count);
2289
2290         /* ensure the branch is active/loaded */
2291         if (!b->branch_tree.tree || !max_active_branches) {
2292                 unload_one_branch();
2293                 load_branch(b);
2294         }
2295
2296         /* file_change* */
2297         while (command_buf.len > 0) {
2298                 if (!prefixcmp(command_buf.buf, "M "))
2299                         file_change_m(b);
2300                 else if (!prefixcmp(command_buf.buf, "D "))
2301                         file_change_d(b);
2302                 else if (!prefixcmp(command_buf.buf, "R "))
2303                         file_change_cr(b, 1);
2304                 else if (!prefixcmp(command_buf.buf, "C "))
2305                         file_change_cr(b, 0);
2306                 else if (!prefixcmp(command_buf.buf, "N "))
2307                         note_change_n(b);
2308                 else if (!strcmp("deleteall", command_buf.buf))
2309                         file_change_deleteall(b);
2310                 else {
2311                         unread_command_buf = 1;
2312                         break;
2313                 }
2314                 if (read_next_command() == EOF)
2315                         break;
2316         }
2317
2318         /* build the tree and the commit */
2319         store_tree(&b->branch_tree);
2320         hashcpy(b->branch_tree.versions[0].sha1,
2321                 b->branch_tree.versions[1].sha1);
2322
2323         strbuf_reset(&new_data);
2324         strbuf_addf(&new_data, "tree %s\n",
2325                 sha1_to_hex(b->branch_tree.versions[1].sha1));
2326         if (!is_null_sha1(b->sha1))
2327                 strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(b->sha1));
2328         while (merge_list) {
2329                 struct hash_list *next = merge_list->next;
2330                 strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(merge_list->sha1));
2331                 free(merge_list);
2332                 merge_list = next;
2333         }
2334         strbuf_addf(&new_data,
2335                 "author %s\n"
2336                 "committer %s\n"
2337                 "\n",
2338                 author ? author : committer, committer);
2339         strbuf_addbuf(&new_data, &msg);
2340         free(author);
2341         free(committer);
2342
2343         if (!store_object(OBJ_COMMIT, &new_data, NULL, b->sha1, next_mark))
2344                 b->pack_id = pack_id;
2345         b->last_commit = object_count_by_type[OBJ_COMMIT];
2346 }
2347
2348 static void parse_new_tag(void)
2349 {
2350         static struct strbuf msg = STRBUF_INIT;
2351         char *sp;
2352         const char *from;
2353         char *tagger;
2354         struct branch *s;
2355         struct tag *t;
2356         uintmax_t from_mark = 0;
2357         unsigned char sha1[20];
2358
2359         /* Obtain the new tag name from the rest of our command */
2360         sp = strchr(command_buf.buf, ' ') + 1;
2361         t = pool_alloc(sizeof(struct tag));
2362         t->next_tag = NULL;
2363         t->name = pool_strdup(sp);
2364         if (last_tag)
2365                 last_tag->next_tag = t;
2366         else
2367                 first_tag = t;
2368         last_tag = t;
2369         read_next_command();
2370
2371         /* from ... */
2372         if (prefixcmp(command_buf.buf, "from "))
2373                 die("Expected from command, got %s", command_buf.buf);
2374         from = strchr(command_buf.buf, ' ') + 1;
2375         s = lookup_branch(from);
2376         if (s) {
2377                 hashcpy(sha1, s->sha1);
2378         } else if (*from == ':') {
2379                 struct object_entry *oe;
2380                 from_mark = strtoumax(from + 1, NULL, 10);
2381                 oe = find_mark(from_mark);
2382                 if (oe->type != OBJ_COMMIT)
2383                         die("Mark :%" PRIuMAX " not a commit", from_mark);
2384                 hashcpy(sha1, oe->sha1);
2385         } else if (!get_sha1(from, sha1)) {
2386                 unsigned long size;
2387                 char *buf;
2388
2389                 buf = read_object_with_reference(sha1,
2390                         commit_type, &size, sha1);
2391                 if (!buf || size < 46)
2392                         die("Not a valid commit: %s", from);
2393                 free(buf);
2394         } else
2395                 die("Invalid ref name or SHA1 expression: %s", from);
2396         read_next_command();
2397
2398         /* tagger ... */
2399         if (!prefixcmp(command_buf.buf, "tagger ")) {
2400                 tagger = parse_ident(command_buf.buf + 7);
2401                 read_next_command();
2402         } else
2403                 tagger = NULL;
2404
2405         /* tag payload/message */
2406         parse_data(&msg);
2407
2408         /* build the tag object */
2409         strbuf_reset(&new_data);
2410
2411         strbuf_addf(&new_data,
2412                     "object %s\n"
2413                     "type %s\n"
2414                     "tag %s\n",
2415                     sha1_to_hex(sha1), commit_type, t->name);
2416         if (tagger)
2417                 strbuf_addf(&new_data,
2418                             "tagger %s\n", tagger);
2419         strbuf_addch(&new_data, '\n');
2420         strbuf_addbuf(&new_data, &msg);
2421         free(tagger);
2422
2423         if (store_object(OBJ_TAG, &new_data, NULL, t->sha1, 0))
2424                 t->pack_id = MAX_PACK_ID;
2425         else
2426                 t->pack_id = pack_id;
2427 }
2428
2429 static void parse_reset_branch(void)
2430 {
2431         struct branch *b;
2432         char *sp;
2433
2434         /* Obtain the branch name from the rest of our command */
2435         sp = strchr(command_buf.buf, ' ') + 1;
2436         b = lookup_branch(sp);
2437         if (b) {
2438                 hashclr(b->sha1);
2439                 hashclr(b->branch_tree.versions[0].sha1);
2440                 hashclr(b->branch_tree.versions[1].sha1);
2441                 if (b->branch_tree.tree) {
2442                         release_tree_content_recursive(b->branch_tree.tree);
2443                         b->branch_tree.tree = NULL;
2444                 }
2445         }
2446         else
2447                 b = new_branch(sp);
2448         read_next_command();
2449         parse_from(b);
2450         if (command_buf.len > 0)
2451                 unread_command_buf = 1;
2452 }
2453
2454 static void parse_checkpoint(void)
2455 {
2456         if (object_count) {
2457                 cycle_packfile();
2458                 dump_branches();
2459                 dump_tags();
2460                 dump_marks();
2461         }
2462         skip_optional_lf();
2463 }
2464
2465 static void parse_progress(void)
2466 {
2467         fwrite(command_buf.buf, 1, command_buf.len, stdout);
2468         fputc('\n', stdout);
2469         fflush(stdout);
2470         skip_optional_lf();
2471 }
2472
2473 static void option_import_marks(const char *marks, int from_stream)
2474 {
2475         if (import_marks_file) {
2476                 if (from_stream)
2477                         die("Only one import-marks command allowed per stream");
2478
2479                 /* read previous mark file */
2480                 if(!import_marks_file_from_stream)
2481                         read_marks();
2482         }
2483
2484         import_marks_file = xstrdup(marks);
2485         import_marks_file_from_stream = from_stream;
2486 }
2487
2488 static void option_date_format(const char *fmt)
2489 {
2490         if (!strcmp(fmt, "raw"))
2491                 whenspec = WHENSPEC_RAW;
2492         else if (!strcmp(fmt, "rfc2822"))
2493                 whenspec = WHENSPEC_RFC2822;
2494         else if (!strcmp(fmt, "now"))
2495                 whenspec = WHENSPEC_NOW;
2496         else
2497                 die("unknown --date-format argument %s", fmt);
2498 }
2499
2500 static void option_max_pack_size(const char *packsize)
2501 {
2502         max_packsize = strtoumax(packsize, NULL, 0) * 1024 * 1024;
2503 }
2504
2505 static void option_depth(const char *depth)
2506 {
2507         max_depth = strtoul(depth, NULL, 0);
2508         if (max_depth > MAX_DEPTH)
2509                 die("--depth cannot exceed %u", MAX_DEPTH);
2510 }
2511
2512 static void option_active_branches(const char *branches)
2513 {
2514         max_active_branches = strtoul(branches, NULL, 0);
2515 }
2516
2517 static void option_export_marks(const char *marks)
2518 {
2519         export_marks_file = xstrdup(marks);
2520 }
2521
2522 static void option_export_pack_edges(const char *edges)
2523 {
2524         if (pack_edges)
2525                 fclose(pack_edges);
2526         pack_edges = fopen(edges, "a");
2527         if (!pack_edges)
2528                 die_errno("Cannot open '%s'", edges);
2529 }
2530
2531 static int parse_one_option(const char *option)
2532 {
2533         if (!prefixcmp(option, "max-pack-size=")) {
2534                 option_max_pack_size(option + 14);
2535         } else if (!prefixcmp(option, "depth=")) {
2536                 option_depth(option + 6);
2537         } else if (!prefixcmp(option, "active-branches=")) {
2538                 option_active_branches(option + 16);
2539         } else if (!prefixcmp(option, "export-pack-edges=")) {
2540                 option_export_pack_edges(option + 18);
2541         } else if (!prefixcmp(option, "quiet")) {
2542                 show_stats = 0;
2543         } else if (!prefixcmp(option, "stats")) {
2544                 show_stats = 1;
2545         } else {
2546                 return 0;
2547         }
2548
2549         return 1;
2550 }
2551
2552 static int parse_one_feature(const char *feature, int from_stream)
2553 {
2554         if (!prefixcmp(feature, "date-format=")) {
2555                 option_date_format(feature + 12);
2556         } else if (!prefixcmp(feature, "import-marks=")) {
2557                 option_import_marks(feature + 13, from_stream);
2558         } else if (!prefixcmp(feature, "export-marks=")) {
2559                 option_export_marks(feature + 13);
2560         } else if (!prefixcmp(feature, "force")) {
2561                 force_update = 1;
2562         } else {
2563                 return 0;
2564         }
2565
2566         return 1;
2567 }
2568
2569 static void parse_feature(void)
2570 {
2571         char *feature = command_buf.buf + 8;
2572
2573         if (seen_data_command)
2574                 die("Got feature command '%s' after data command", feature);
2575
2576         if (parse_one_feature(feature, 1))
2577                 return;
2578
2579         die("This version of fast-import does not support feature %s.", feature);
2580 }
2581
2582 static void parse_option(void)
2583 {
2584         char *option = command_buf.buf + 11;
2585
2586         if (seen_data_command)
2587                 die("Got option command '%s' after data command", option);
2588
2589         if (parse_one_option(option))
2590                 return;
2591
2592         die("This version of fast-import does not support option: %s", option);
2593 }
2594
2595 static int git_pack_config(const char *k, const char *v, void *cb)
2596 {
2597         if (!strcmp(k, "pack.depth")) {
2598                 max_depth = git_config_int(k, v);
2599                 if (max_depth > MAX_DEPTH)
2600                         max_depth = MAX_DEPTH;
2601                 return 0;
2602         }
2603         if (!strcmp(k, "pack.compression")) {
2604                 int level = git_config_int(k, v);
2605                 if (level == -1)
2606                         level = Z_DEFAULT_COMPRESSION;
2607                 else if (level < 0 || level > Z_BEST_COMPRESSION)
2608                         die("bad pack compression level %d", level);
2609                 pack_compression_level = level;
2610                 pack_compression_seen = 1;
2611                 return 0;
2612         }
2613         return git_default_config(k, v, cb);
2614 }
2615
2616 static const char fast_import_usage[] =
2617 "git fast-import [--date-format=f] [--max-pack-size=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file]";
2618
2619 static void parse_argv(void)
2620 {
2621         unsigned int i;
2622
2623         for (i = 1; i < global_argc; i++) {
2624                 const char *a = global_argv[i];
2625
2626                 if (*a != '-' || !strcmp(a, "--"))
2627                         break;
2628
2629                 if (parse_one_option(a + 2))
2630                         continue;
2631
2632                 if (parse_one_feature(a + 2, 0))
2633                         continue;
2634
2635                 die("unknown option %s", a);
2636         }
2637         if (i != global_argc)
2638                 usage(fast_import_usage);
2639
2640         seen_data_command = 1;
2641         if (import_marks_file)
2642                 read_marks();
2643 }
2644
2645 int main(int argc, const char **argv)
2646 {
2647         unsigned int i;
2648
2649         git_extract_argv0_path(argv[0]);
2650
2651         if (argc == 2 && !strcmp(argv[1], "-h"))
2652                 usage(fast_import_usage);
2653
2654         setup_git_directory();
2655         git_config(git_pack_config, NULL);
2656         if (!pack_compression_seen && core_compression_seen)
2657                 pack_compression_level = core_compression_level;
2658
2659         alloc_objects(object_entry_alloc);
2660         strbuf_init(&command_buf, 0);
2661         atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
2662         branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
2663         avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
2664         marks = pool_calloc(1, sizeof(struct mark_set));
2665
2666         global_argc = argc;
2667         global_argv = argv;
2668
2669         rc_free = pool_alloc(cmd_save * sizeof(*rc_free));
2670         for (i = 0; i < (cmd_save - 1); i++)
2671                 rc_free[i].next = &rc_free[i + 1];
2672         rc_free[cmd_save - 1].next = NULL;
2673
2674         prepare_packed_git();
2675         start_packfile();
2676         set_die_routine(die_nicely);
2677         while (read_next_command() != EOF) {
2678                 if (!strcmp("blob", command_buf.buf))
2679                         parse_new_blob();
2680                 else if (!prefixcmp(command_buf.buf, "commit "))
2681                         parse_new_commit();
2682                 else if (!prefixcmp(command_buf.buf, "tag "))
2683                         parse_new_tag();
2684                 else if (!prefixcmp(command_buf.buf, "reset "))
2685                         parse_reset_branch();
2686                 else if (!strcmp("checkpoint", command_buf.buf))
2687                         parse_checkpoint();
2688                 else if (!prefixcmp(command_buf.buf, "progress "))
2689                         parse_progress();
2690                 else if (!prefixcmp(command_buf.buf, "feature "))
2691                         parse_feature();
2692                 else if (!prefixcmp(command_buf.buf, "option git "))
2693                         parse_option();
2694                 else if (!prefixcmp(command_buf.buf, "option "))
2695                         /* ignore non-git options*/;
2696                 else
2697                         die("Unsupported command: %s", command_buf.buf);
2698         }
2699
2700         /* argv hasn't been parsed yet, do so */
2701         if (!seen_data_command)
2702                 parse_argv();
2703
2704         end_packfile();
2705
2706         dump_branches();
2707         dump_tags();
2708         unkeep_all_packs();
2709         dump_marks();
2710
2711         if (pack_edges)
2712                 fclose(pack_edges);
2713
2714         if (show_stats) {
2715                 uintmax_t total_count = 0, duplicate_count = 0;
2716                 for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
2717                         total_count += object_count_by_type[i];
2718                 for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
2719                         duplicate_count += duplicate_count_by_type[i];
2720
2721                 fprintf(stderr, "%s statistics:\n", argv[0]);
2722                 fprintf(stderr, "---------------------------------------------------------------------\n");
2723                 fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
2724                 fprintf(stderr, "Total objects:   %10" PRIuMAX " (%10" PRIuMAX " duplicates                  )\n", total_count, duplicate_count);
2725                 fprintf(stderr, "      blobs  :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB]);
2726                 fprintf(stderr, "      trees  :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE]);
2727                 fprintf(stderr, "      commits:   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT]);
2728                 fprintf(stderr, "      tags   :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG]);
2729                 fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
2730                 fprintf(stderr, "      marks:     %10" PRIuMAX " (%10" PRIuMAX " unique    )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
2731                 fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
2732                 fprintf(stderr, "Memory total:    %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
2733                 fprintf(stderr, "       pools:    %10lu KiB\n", (unsigned long)(total_allocd/1024));
2734                 fprintf(stderr, "     objects:    %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
2735                 fprintf(stderr, "---------------------------------------------------------------------\n");
2736                 pack_report();
2737                 fprintf(stderr, "---------------------------------------------------------------------\n");
2738                 fprintf(stderr, "\n");
2739         }
2740
2741         return failure ? 1 : 0;
2742 }