Merge branch 'dk/blame-el' into pu
[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 *mark_file;
324 static const char *input_file;
325
326 /* Our last blob */
327 static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
328
329 /* Tree management */
330 static unsigned int tree_entry_alloc = 1000;
331 static void *avail_tree_entry;
332 static unsigned int avail_tree_table_sz = 100;
333 static struct avail_tree_content **avail_tree_table;
334 static struct strbuf old_tree = STRBUF_INIT;
335 static struct strbuf new_tree = STRBUF_INIT;
336
337 /* Branch data */
338 static unsigned long max_active_branches = 5;
339 static unsigned long cur_active_branches;
340 static unsigned long branch_table_sz = 1039;
341 static struct branch **branch_table;
342 static struct branch *active_branches;
343
344 /* Tag data */
345 static struct tag *first_tag;
346 static struct tag *last_tag;
347
348 /* Input stream parsing */
349 static whenspec_type whenspec = WHENSPEC_RAW;
350 static struct strbuf command_buf = STRBUF_INIT;
351 static int unread_command_buf;
352 static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
353 static struct recent_command *cmd_tail = &cmd_hist;
354 static struct recent_command *rc_free;
355 static unsigned int cmd_save = 100;
356 static uintmax_t next_mark;
357 static struct strbuf new_data = STRBUF_INIT;
358 static int options_enabled;
359 static int seen_non_option_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 (mark_file)
466                 fprintf(rpt, "  exported to %s\n", mark_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 (!mark_file)
1614                 return;
1615
1616         mark_fd = hold_lock_file_for_update(&mark_lock, mark_file, 0);
1617         if (mark_fd < 0) {
1618                 failure |= error("Unable to write marks file %s: %s",
1619                         mark_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                         mark_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                         mark_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                         mark_file, strerror(saved_errno));
1653                 return;
1654         }
1655 }
1656
1657 static void read_marks(void)
1658 {
1659         char line[512];
1660         FILE *f = fopen(input_file, "r");
1661         if (!f)
1662                 die_errno("cannot read '%s'", input_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_non_option_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
1802         errno = 0;
1803
1804         strtoul(src, &endp, 10);
1805         if (errno || endp == src || *endp != ' ')
1806                 return -1;
1807
1808         src = endp + 1;
1809         if (*src != '-' && *src != '+')
1810                 return -1;
1811
1812         strtoul(src + 1, &endp, 10);
1813         if (errno || endp == src || *endp || (endp - orig_src) >= maxlen)
1814                 return -1;
1815
1816         strcpy(result, orig_src);
1817         return 0;
1818 }
1819
1820 static char *parse_ident(const char *buf)
1821 {
1822         const char *gt;
1823         size_t name_len;
1824         char *ident;
1825
1826         gt = strrchr(buf, '>');
1827         if (!gt)
1828                 die("Missing > in ident string: %s", buf);
1829         gt++;
1830         if (*gt != ' ')
1831                 die("Missing space after > in ident string: %s", buf);
1832         gt++;
1833         name_len = gt - buf;
1834         ident = xmalloc(name_len + 24);
1835         strncpy(ident, buf, name_len);
1836
1837         switch (whenspec) {
1838         case WHENSPEC_RAW:
1839                 if (validate_raw_date(gt, ident + name_len, 24) < 0)
1840                         die("Invalid raw date \"%s\" in ident: %s", gt, buf);
1841                 break;
1842         case WHENSPEC_RFC2822:
1843                 if (parse_date(gt, ident + name_len, 24) < 0)
1844                         die("Invalid rfc2822 date \"%s\" in ident: %s", gt, buf);
1845                 break;
1846         case WHENSPEC_NOW:
1847                 if (strcmp("now", gt))
1848                         die("Date in ident must be 'now': %s", buf);
1849                 datestamp(ident + name_len, 24);
1850                 break;
1851         }
1852
1853         return ident;
1854 }
1855
1856 static void parse_new_blob(void)
1857 {
1858         static struct strbuf buf = STRBUF_INIT;
1859
1860         read_next_command();
1861         parse_mark();
1862         parse_data(&buf);
1863         store_object(OBJ_BLOB, &buf, &last_blob, NULL, next_mark);
1864 }
1865
1866 static void unload_one_branch(void)
1867 {
1868         while (cur_active_branches
1869                 && cur_active_branches >= max_active_branches) {
1870                 uintmax_t min_commit = ULONG_MAX;
1871                 struct branch *e, *l = NULL, *p = NULL;
1872
1873                 for (e = active_branches; e; e = e->active_next_branch) {
1874                         if (e->last_commit < min_commit) {
1875                                 p = l;
1876                                 min_commit = e->last_commit;
1877                         }
1878                         l = e;
1879                 }
1880
1881                 if (p) {
1882                         e = p->active_next_branch;
1883                         p->active_next_branch = e->active_next_branch;
1884                 } else {
1885                         e = active_branches;
1886                         active_branches = e->active_next_branch;
1887                 }
1888                 e->active = 0;
1889                 e->active_next_branch = NULL;
1890                 if (e->branch_tree.tree) {
1891                         release_tree_content_recursive(e->branch_tree.tree);
1892                         e->branch_tree.tree = NULL;
1893                 }
1894                 cur_active_branches--;
1895         }
1896 }
1897
1898 static void load_branch(struct branch *b)
1899 {
1900         load_tree(&b->branch_tree);
1901         if (!b->active) {
1902                 b->active = 1;
1903                 b->active_next_branch = active_branches;
1904                 active_branches = b;
1905                 cur_active_branches++;
1906                 branch_load_count++;
1907         }
1908 }
1909
1910 static void file_change_m(struct branch *b)
1911 {
1912         const char *p = command_buf.buf + 2;
1913         static struct strbuf uq = STRBUF_INIT;
1914         const char *endp;
1915         struct object_entry *oe = oe;
1916         unsigned char sha1[20];
1917         uint16_t mode, inline_data = 0;
1918
1919         p = get_mode(p, &mode);
1920         if (!p)
1921                 die("Corrupt mode: %s", command_buf.buf);
1922         switch (mode) {
1923         case 0644:
1924         case 0755:
1925                 mode |= S_IFREG;
1926         case S_IFREG | 0644:
1927         case S_IFREG | 0755:
1928         case S_IFLNK:
1929         case S_IFGITLINK:
1930                 /* ok */
1931                 break;
1932         default:
1933                 die("Corrupt mode: %s", command_buf.buf);
1934         }
1935
1936         if (*p == ':') {
1937                 char *x;
1938                 oe = find_mark(strtoumax(p + 1, &x, 10));
1939                 hashcpy(sha1, oe->sha1);
1940                 p = x;
1941         } else if (!prefixcmp(p, "inline")) {
1942                 inline_data = 1;
1943                 p += 6;
1944         } else {
1945                 if (get_sha1_hex(p, sha1))
1946                         die("Invalid SHA1: %s", command_buf.buf);
1947                 oe = find_object(sha1);
1948                 p += 40;
1949         }
1950         if (*p++ != ' ')
1951                 die("Missing space after SHA1: %s", command_buf.buf);
1952
1953         strbuf_reset(&uq);
1954         if (!unquote_c_style(&uq, p, &endp)) {
1955                 if (*endp)
1956                         die("Garbage after path in: %s", command_buf.buf);
1957                 p = uq.buf;
1958         }
1959
1960         if (S_ISGITLINK(mode)) {
1961                 if (inline_data)
1962                         die("Git links cannot be specified 'inline': %s",
1963                                 command_buf.buf);
1964                 else if (oe) {
1965                         if (oe->type != OBJ_COMMIT)
1966                                 die("Not a commit (actually a %s): %s",
1967                                         typename(oe->type), command_buf.buf);
1968                 }
1969                 /*
1970                  * Accept the sha1 without checking; it expected to be in
1971                  * another repository.
1972                  */
1973         } else if (inline_data) {
1974                 static struct strbuf buf = STRBUF_INIT;
1975
1976                 if (p != uq.buf) {
1977                         strbuf_addstr(&uq, p);
1978                         p = uq.buf;
1979                 }
1980                 read_next_command();
1981                 parse_data(&buf);
1982                 store_object(OBJ_BLOB, &buf, &last_blob, sha1, 0);
1983         } else if (oe) {
1984                 if (oe->type != OBJ_BLOB)
1985                         die("Not a blob (actually a %s): %s",
1986                                 typename(oe->type), command_buf.buf);
1987         } else {
1988                 enum object_type type = sha1_object_info(sha1, NULL);
1989                 if (type < 0)
1990                         die("Blob not found: %s", command_buf.buf);
1991                 if (type != OBJ_BLOB)
1992                         die("Not a blob (actually a %s): %s",
1993                             typename(type), command_buf.buf);
1994         }
1995
1996         tree_content_set(&b->branch_tree, p, sha1, mode, NULL);
1997 }
1998
1999 static void file_change_d(struct branch *b)
2000 {
2001         const char *p = command_buf.buf + 2;
2002         static struct strbuf uq = STRBUF_INIT;
2003         const char *endp;
2004
2005         strbuf_reset(&uq);
2006         if (!unquote_c_style(&uq, p, &endp)) {
2007                 if (*endp)
2008                         die("Garbage after path in: %s", command_buf.buf);
2009                 p = uq.buf;
2010         }
2011         tree_content_remove(&b->branch_tree, p, NULL);
2012 }
2013
2014 static void file_change_cr(struct branch *b, int rename)
2015 {
2016         const char *s, *d;
2017         static struct strbuf s_uq = STRBUF_INIT;
2018         static struct strbuf d_uq = STRBUF_INIT;
2019         const char *endp;
2020         struct tree_entry leaf;
2021
2022         s = command_buf.buf + 2;
2023         strbuf_reset(&s_uq);
2024         if (!unquote_c_style(&s_uq, s, &endp)) {
2025                 if (*endp != ' ')
2026                         die("Missing space after source: %s", command_buf.buf);
2027         } else {
2028                 endp = strchr(s, ' ');
2029                 if (!endp)
2030                         die("Missing space after source: %s", command_buf.buf);
2031                 strbuf_add(&s_uq, s, endp - s);
2032         }
2033         s = s_uq.buf;
2034
2035         endp++;
2036         if (!*endp)
2037                 die("Missing dest: %s", command_buf.buf);
2038
2039         d = endp;
2040         strbuf_reset(&d_uq);
2041         if (!unquote_c_style(&d_uq, d, &endp)) {
2042                 if (*endp)
2043                         die("Garbage after dest in: %s", command_buf.buf);
2044                 d = d_uq.buf;
2045         }
2046
2047         memset(&leaf, 0, sizeof(leaf));
2048         if (rename)
2049                 tree_content_remove(&b->branch_tree, s, &leaf);
2050         else
2051                 tree_content_get(&b->branch_tree, s, &leaf);
2052         if (!leaf.versions[1].mode)
2053                 die("Path %s not in branch", s);
2054         tree_content_set(&b->branch_tree, d,
2055                 leaf.versions[1].sha1,
2056                 leaf.versions[1].mode,
2057                 leaf.tree);
2058 }
2059
2060 static void note_change_n(struct branch *b)
2061 {
2062         const char *p = command_buf.buf + 2;
2063         static struct strbuf uq = STRBUF_INIT;
2064         struct object_entry *oe = oe;
2065         struct branch *s;
2066         unsigned char sha1[20], commit_sha1[20];
2067         uint16_t inline_data = 0;
2068
2069         /* <dataref> or 'inline' */
2070         if (*p == ':') {
2071                 char *x;
2072                 oe = find_mark(strtoumax(p + 1, &x, 10));
2073                 hashcpy(sha1, oe->sha1);
2074                 p = x;
2075         } else if (!prefixcmp(p, "inline")) {
2076                 inline_data = 1;
2077                 p += 6;
2078         } else {
2079                 if (get_sha1_hex(p, sha1))
2080                         die("Invalid SHA1: %s", command_buf.buf);
2081                 oe = find_object(sha1);
2082                 p += 40;
2083         }
2084         if (*p++ != ' ')
2085                 die("Missing space after SHA1: %s", command_buf.buf);
2086
2087         /* <committish> */
2088         s = lookup_branch(p);
2089         if (s) {
2090                 hashcpy(commit_sha1, s->sha1);
2091         } else if (*p == ':') {
2092                 uintmax_t commit_mark = strtoumax(p + 1, NULL, 10);
2093                 struct object_entry *commit_oe = find_mark(commit_mark);
2094                 if (commit_oe->type != OBJ_COMMIT)
2095                         die("Mark :%" PRIuMAX " not a commit", commit_mark);
2096                 hashcpy(commit_sha1, commit_oe->sha1);
2097         } else if (!get_sha1(p, commit_sha1)) {
2098                 unsigned long size;
2099                 char *buf = read_object_with_reference(commit_sha1,
2100                         commit_type, &size, commit_sha1);
2101                 if (!buf || size < 46)
2102                         die("Not a valid commit: %s", p);
2103                 free(buf);
2104         } else
2105                 die("Invalid ref name or SHA1 expression: %s", p);
2106
2107         if (inline_data) {
2108                 static struct strbuf buf = STRBUF_INIT;
2109
2110                 if (p != uq.buf) {
2111                         strbuf_addstr(&uq, p);
2112                         p = uq.buf;
2113                 }
2114                 read_next_command();
2115                 parse_data(&buf);
2116                 store_object(OBJ_BLOB, &buf, &last_blob, sha1, 0);
2117         } else if (oe) {
2118                 if (oe->type != OBJ_BLOB)
2119                         die("Not a blob (actually a %s): %s",
2120                                 typename(oe->type), command_buf.buf);
2121         } else {
2122                 enum object_type type = sha1_object_info(sha1, NULL);
2123                 if (type < 0)
2124                         die("Blob not found: %s", command_buf.buf);
2125                 if (type != OBJ_BLOB)
2126                         die("Not a blob (actually a %s): %s",
2127                             typename(type), command_buf.buf);
2128         }
2129
2130         tree_content_set(&b->branch_tree, sha1_to_hex(commit_sha1), sha1,
2131                 S_IFREG | 0644, NULL);
2132 }
2133
2134 static void file_change_deleteall(struct branch *b)
2135 {
2136         release_tree_content_recursive(b->branch_tree.tree);
2137         hashclr(b->branch_tree.versions[0].sha1);
2138         hashclr(b->branch_tree.versions[1].sha1);
2139         load_tree(&b->branch_tree);
2140 }
2141
2142 static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2143 {
2144         if (!buf || size < 46)
2145                 die("Not a valid commit: %s", sha1_to_hex(b->sha1));
2146         if (memcmp("tree ", buf, 5)
2147                 || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
2148                 die("The commit %s is corrupt", sha1_to_hex(b->sha1));
2149         hashcpy(b->branch_tree.versions[0].sha1,
2150                 b->branch_tree.versions[1].sha1);
2151 }
2152
2153 static void parse_from_existing(struct branch *b)
2154 {
2155         if (is_null_sha1(b->sha1)) {
2156                 hashclr(b->branch_tree.versions[0].sha1);
2157                 hashclr(b->branch_tree.versions[1].sha1);
2158         } else {
2159                 unsigned long size;
2160                 char *buf;
2161
2162                 buf = read_object_with_reference(b->sha1,
2163                         commit_type, &size, b->sha1);
2164                 parse_from_commit(b, buf, size);
2165                 free(buf);
2166         }
2167 }
2168
2169 static int parse_from(struct branch *b)
2170 {
2171         const char *from;
2172         struct branch *s;
2173
2174         if (prefixcmp(command_buf.buf, "from "))
2175                 return 0;
2176
2177         if (b->branch_tree.tree) {
2178                 release_tree_content_recursive(b->branch_tree.tree);
2179                 b->branch_tree.tree = NULL;
2180         }
2181
2182         from = strchr(command_buf.buf, ' ') + 1;
2183         s = lookup_branch(from);
2184         if (b == s)
2185                 die("Can't create a branch from itself: %s", b->name);
2186         else if (s) {
2187                 unsigned char *t = s->branch_tree.versions[1].sha1;
2188                 hashcpy(b->sha1, s->sha1);
2189                 hashcpy(b->branch_tree.versions[0].sha1, t);
2190                 hashcpy(b->branch_tree.versions[1].sha1, t);
2191         } else if (*from == ':') {
2192                 uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2193                 struct object_entry *oe = find_mark(idnum);
2194                 if (oe->type != OBJ_COMMIT)
2195                         die("Mark :%" PRIuMAX " not a commit", idnum);
2196                 hashcpy(b->sha1, oe->sha1);
2197                 if (oe->pack_id != MAX_PACK_ID) {
2198                         unsigned long size;
2199                         char *buf = gfi_unpack_entry(oe, &size);
2200                         parse_from_commit(b, buf, size);
2201                         free(buf);
2202                 } else
2203                         parse_from_existing(b);
2204         } else if (!get_sha1(from, b->sha1))
2205                 parse_from_existing(b);
2206         else
2207                 die("Invalid ref name or SHA1 expression: %s", from);
2208
2209         read_next_command();
2210         return 1;
2211 }
2212
2213 static struct hash_list *parse_merge(unsigned int *count)
2214 {
2215         struct hash_list *list = NULL, *n, *e = e;
2216         const char *from;
2217         struct branch *s;
2218
2219         *count = 0;
2220         while (!prefixcmp(command_buf.buf, "merge ")) {
2221                 from = strchr(command_buf.buf, ' ') + 1;
2222                 n = xmalloc(sizeof(*n));
2223                 s = lookup_branch(from);
2224                 if (s)
2225                         hashcpy(n->sha1, s->sha1);
2226                 else if (*from == ':') {
2227                         uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2228                         struct object_entry *oe = find_mark(idnum);
2229                         if (oe->type != OBJ_COMMIT)
2230                                 die("Mark :%" PRIuMAX " not a commit", idnum);
2231                         hashcpy(n->sha1, oe->sha1);
2232                 } else if (!get_sha1(from, n->sha1)) {
2233                         unsigned long size;
2234                         char *buf = read_object_with_reference(n->sha1,
2235                                 commit_type, &size, n->sha1);
2236                         if (!buf || size < 46)
2237                                 die("Not a valid commit: %s", from);
2238                         free(buf);
2239                 } else
2240                         die("Invalid ref name or SHA1 expression: %s", from);
2241
2242                 n->next = NULL;
2243                 if (list)
2244                         e->next = n;
2245                 else
2246                         list = n;
2247                 e = n;
2248                 (*count)++;
2249                 read_next_command();
2250         }
2251         return list;
2252 }
2253
2254 static void parse_new_commit(void)
2255 {
2256         static struct strbuf msg = STRBUF_INIT;
2257         struct branch *b;
2258         char *sp;
2259         char *author = NULL;
2260         char *committer = NULL;
2261         struct hash_list *merge_list = NULL;
2262         unsigned int merge_count;
2263
2264         /* Obtain the branch name from the rest of our command */
2265         sp = strchr(command_buf.buf, ' ') + 1;
2266         b = lookup_branch(sp);
2267         if (!b)
2268                 b = new_branch(sp);
2269
2270         read_next_command();
2271         parse_mark();
2272         if (!prefixcmp(command_buf.buf, "author ")) {
2273                 author = parse_ident(command_buf.buf + 7);
2274                 read_next_command();
2275         }
2276         if (!prefixcmp(command_buf.buf, "committer ")) {
2277                 committer = parse_ident(command_buf.buf + 10);
2278                 read_next_command();
2279         }
2280         if (!committer)
2281                 die("Expected committer but didn't get one");
2282         parse_data(&msg);
2283         read_next_command();
2284         parse_from(b);
2285         merge_list = parse_merge(&merge_count);
2286
2287         /* ensure the branch is active/loaded */
2288         if (!b->branch_tree.tree || !max_active_branches) {
2289                 unload_one_branch();
2290                 load_branch(b);
2291         }
2292
2293         /* file_change* */
2294         while (command_buf.len > 0) {
2295                 if (!prefixcmp(command_buf.buf, "M "))
2296                         file_change_m(b);
2297                 else if (!prefixcmp(command_buf.buf, "D "))
2298                         file_change_d(b);
2299                 else if (!prefixcmp(command_buf.buf, "R "))
2300                         file_change_cr(b, 1);
2301                 else if (!prefixcmp(command_buf.buf, "C "))
2302                         file_change_cr(b, 0);
2303                 else if (!prefixcmp(command_buf.buf, "N "))
2304                         note_change_n(b);
2305                 else if (!strcmp("deleteall", command_buf.buf))
2306                         file_change_deleteall(b);
2307                 else {
2308                         unread_command_buf = 1;
2309                         break;
2310                 }
2311                 if (read_next_command() == EOF)
2312                         break;
2313         }
2314
2315         /* build the tree and the commit */
2316         store_tree(&b->branch_tree);
2317         hashcpy(b->branch_tree.versions[0].sha1,
2318                 b->branch_tree.versions[1].sha1);
2319
2320         strbuf_reset(&new_data);
2321         strbuf_addf(&new_data, "tree %s\n",
2322                 sha1_to_hex(b->branch_tree.versions[1].sha1));
2323         if (!is_null_sha1(b->sha1))
2324                 strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(b->sha1));
2325         while (merge_list) {
2326                 struct hash_list *next = merge_list->next;
2327                 strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(merge_list->sha1));
2328                 free(merge_list);
2329                 merge_list = next;
2330         }
2331         strbuf_addf(&new_data,
2332                 "author %s\n"
2333                 "committer %s\n"
2334                 "\n",
2335                 author ? author : committer, committer);
2336         strbuf_addbuf(&new_data, &msg);
2337         free(author);
2338         free(committer);
2339
2340         if (!store_object(OBJ_COMMIT, &new_data, NULL, b->sha1, next_mark))
2341                 b->pack_id = pack_id;
2342         b->last_commit = object_count_by_type[OBJ_COMMIT];
2343 }
2344
2345 static void parse_new_tag(void)
2346 {
2347         static struct strbuf msg = STRBUF_INIT;
2348         char *sp;
2349         const char *from;
2350         char *tagger;
2351         struct branch *s;
2352         struct tag *t;
2353         uintmax_t from_mark = 0;
2354         unsigned char sha1[20];
2355
2356         /* Obtain the new tag name from the rest of our command */
2357         sp = strchr(command_buf.buf, ' ') + 1;
2358         t = pool_alloc(sizeof(struct tag));
2359         t->next_tag = NULL;
2360         t->name = pool_strdup(sp);
2361         if (last_tag)
2362                 last_tag->next_tag = t;
2363         else
2364                 first_tag = t;
2365         last_tag = t;
2366         read_next_command();
2367
2368         /* from ... */
2369         if (prefixcmp(command_buf.buf, "from "))
2370                 die("Expected from command, got %s", command_buf.buf);
2371         from = strchr(command_buf.buf, ' ') + 1;
2372         s = lookup_branch(from);
2373         if (s) {
2374                 hashcpy(sha1, s->sha1);
2375         } else if (*from == ':') {
2376                 struct object_entry *oe;
2377                 from_mark = strtoumax(from + 1, NULL, 10);
2378                 oe = find_mark(from_mark);
2379                 if (oe->type != OBJ_COMMIT)
2380                         die("Mark :%" PRIuMAX " not a commit", from_mark);
2381                 hashcpy(sha1, oe->sha1);
2382         } else if (!get_sha1(from, sha1)) {
2383                 unsigned long size;
2384                 char *buf;
2385
2386                 buf = read_object_with_reference(sha1,
2387                         commit_type, &size, sha1);
2388                 if (!buf || size < 46)
2389                         die("Not a valid commit: %s", from);
2390                 free(buf);
2391         } else
2392                 die("Invalid ref name or SHA1 expression: %s", from);
2393         read_next_command();
2394
2395         /* tagger ... */
2396         if (!prefixcmp(command_buf.buf, "tagger ")) {
2397                 tagger = parse_ident(command_buf.buf + 7);
2398                 read_next_command();
2399         } else
2400                 tagger = NULL;
2401
2402         /* tag payload/message */
2403         parse_data(&msg);
2404
2405         /* build the tag object */
2406         strbuf_reset(&new_data);
2407
2408         strbuf_addf(&new_data,
2409                     "object %s\n"
2410                     "type %s\n"
2411                     "tag %s\n",
2412                     sha1_to_hex(sha1), commit_type, t->name);
2413         if (tagger)
2414                 strbuf_addf(&new_data,
2415                             "tagger %s\n", tagger);
2416         strbuf_addch(&new_data, '\n');
2417         strbuf_addbuf(&new_data, &msg);
2418         free(tagger);
2419
2420         if (store_object(OBJ_TAG, &new_data, NULL, t->sha1, 0))
2421                 t->pack_id = MAX_PACK_ID;
2422         else
2423                 t->pack_id = pack_id;
2424 }
2425
2426 static void parse_reset_branch(void)
2427 {
2428         struct branch *b;
2429         char *sp;
2430
2431         /* Obtain the branch name from the rest of our command */
2432         sp = strchr(command_buf.buf, ' ') + 1;
2433         b = lookup_branch(sp);
2434         if (b) {
2435                 hashclr(b->sha1);
2436                 hashclr(b->branch_tree.versions[0].sha1);
2437                 hashclr(b->branch_tree.versions[1].sha1);
2438                 if (b->branch_tree.tree) {
2439                         release_tree_content_recursive(b->branch_tree.tree);
2440                         b->branch_tree.tree = NULL;
2441                 }
2442         }
2443         else
2444                 b = new_branch(sp);
2445         read_next_command();
2446         parse_from(b);
2447         if (command_buf.len > 0)
2448                 unread_command_buf = 1;
2449 }
2450
2451 static void parse_checkpoint(void)
2452 {
2453         if (object_count) {
2454                 cycle_packfile();
2455                 dump_branches();
2456                 dump_tags();
2457                 dump_marks();
2458         }
2459         skip_optional_lf();
2460 }
2461
2462 static void parse_progress(void)
2463 {
2464         fwrite(command_buf.buf, 1, command_buf.len, stdout);
2465         fputc('\n', stdout);
2466         fflush(stdout);
2467         skip_optional_lf();
2468 }
2469
2470 static void option_import_marks(const char *marks)
2471 {
2472         input_file = xstrdup(marks);
2473 }
2474
2475 static void option_date_format(const char *fmt)
2476 {
2477         if (!strcmp(fmt, "raw"))
2478                 whenspec = WHENSPEC_RAW;
2479         else if (!strcmp(fmt, "rfc2822"))
2480                 whenspec = WHENSPEC_RFC2822;
2481         else if (!strcmp(fmt, "now"))
2482                 whenspec = WHENSPEC_NOW;
2483         else
2484                 die("unknown --date-format argument %s", fmt);
2485 }
2486
2487 static void option_max_pack_size(const char *packsize)
2488 {
2489         max_packsize = strtoumax(packsize, NULL, 0) * 1024 * 1024;
2490 }
2491
2492 static void option_depth(const char *depth)
2493 {
2494         max_depth = strtoul(depth, NULL, 0);
2495         if (max_depth > MAX_DEPTH)
2496                 die("--depth cannot exceed %u", MAX_DEPTH);
2497 }
2498
2499 static void option_active_branches(const char *branches)
2500 {
2501         max_active_branches = strtoul(branches, NULL, 0);
2502 }
2503
2504 static void option_export_marks(const char *marks)
2505 {
2506         mark_file = xstrdup(marks);
2507 }
2508
2509 static void option_export_pack_edges(const char *edges)
2510 {
2511         if (pack_edges)
2512                 fclose(pack_edges);
2513         pack_edges = fopen(edges, "a");
2514         if (!pack_edges)
2515                 die_errno("Cannot open '%s'", edges);
2516 }
2517
2518 static void parse_one_option(const char *option, int optional)
2519 {
2520         if (!prefixcmp(option, "date-format=")) {
2521                 option_date_format(option + 12);
2522         } else if (!prefixcmp(option, "max-pack-size=")) {
2523                 option_max_pack_size(option + 14);
2524         } else if (!prefixcmp(option, "depth=")) {
2525                 option_depth(option + 6);
2526         } else if (!prefixcmp(option, "active-branches=")) {
2527                 option_active_branches(option + 16);
2528         } else if (!prefixcmp(option, "import-marks=")) {
2529                 option_import_marks(option + 13);
2530         } else if (!prefixcmp(option, "export-marks=")) {
2531                 option_export_marks(option + 13);
2532         } else if (!prefixcmp(option, "export-pack-edges=")) {
2533                 option_export_pack_edges(option + 18);
2534         } else if (!prefixcmp(option, "force")) {
2535                 force_update = 1;
2536         } else if (!prefixcmp(option, "quiet")) {
2537                 show_stats = 0;
2538         } else if (!prefixcmp(option, "stats")) {
2539                 show_stats = 1;
2540         } else if (!optional) {
2541                 die("Unsupported option: %s", option);
2542         }
2543 }
2544
2545 static void parse_feature(void)
2546 {
2547         char *feature = command_buf.buf + 8;
2548
2549         if (!prefixcmp(feature, "date-format=")) {
2550                 option_date_format(feature + 12);
2551         } else if (!strcmp("git-options", feature)) {
2552                 options_enabled = 1;
2553         } else {
2554                 die("This version of fast-import does not support feature %s.", feature);
2555         }
2556 }
2557
2558 static void parse_option(void)
2559 {
2560         char *option = command_buf.buf + 11;
2561
2562         if (!options_enabled)
2563                 die("Got option command '%s' before options feature'", option);
2564
2565         if (seen_non_option_command)
2566                 die("Got option command '%s' after non-option command", option);
2567
2568         /* ignore unknown options, instead of erroring */
2569         parse_one_option(option, 1);
2570 }
2571
2572 static void parse_nongit_option(void)
2573 {
2574         /* do nothing */
2575 }
2576
2577 static int git_pack_config(const char *k, const char *v, void *cb)
2578 {
2579         if (!strcmp(k, "pack.depth")) {
2580                 max_depth = git_config_int(k, v);
2581                 if (max_depth > MAX_DEPTH)
2582                         max_depth = MAX_DEPTH;
2583                 return 0;
2584         }
2585         if (!strcmp(k, "pack.compression")) {
2586                 int level = git_config_int(k, v);
2587                 if (level == -1)
2588                         level = Z_DEFAULT_COMPRESSION;
2589                 else if (level < 0 || level > Z_BEST_COMPRESSION)
2590                         die("bad pack compression level %d", level);
2591                 pack_compression_level = level;
2592                 pack_compression_seen = 1;
2593                 return 0;
2594         }
2595         return git_default_config(k, v, cb);
2596 }
2597
2598 static const char fast_import_usage[] =
2599 "git fast-import [--date-format=f] [--max-pack-size=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file]";
2600
2601 static void parse_argv(void)
2602 {
2603         unsigned int i;
2604
2605         for (i = 1; i < global_argc; i++) {
2606                 const char *a = global_argv[i];
2607
2608                 if (*a != '-' || !strcmp(a, "--"))
2609                         break;
2610
2611                 /* error on unknown options */
2612                 parse_one_option(a + 2, 0);
2613         }
2614         if (i != global_argc)
2615                 usage(fast_import_usage);
2616
2617         seen_non_option_command = 1;
2618         if (input_file)
2619                 read_marks();
2620 }
2621
2622 int main(int argc, const char **argv)
2623 {
2624         unsigned int i;
2625
2626         git_extract_argv0_path(argv[0]);
2627
2628         setup_git_directory();
2629         git_config(git_pack_config, NULL);
2630         if (!pack_compression_seen && core_compression_seen)
2631                 pack_compression_level = core_compression_level;
2632
2633         alloc_objects(object_entry_alloc);
2634         strbuf_init(&command_buf, 0);
2635         atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
2636         branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
2637         avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
2638         marks = pool_calloc(1, sizeof(struct mark_set));
2639
2640         global_argc = argc;
2641         global_argv = argv;
2642
2643         rc_free = pool_alloc(cmd_save * sizeof(*rc_free));
2644         for (i = 0; i < (cmd_save - 1); i++)
2645                 rc_free[i].next = &rc_free[i + 1];
2646         rc_free[cmd_save - 1].next = NULL;
2647
2648         prepare_packed_git();
2649         start_packfile();
2650         set_die_routine(die_nicely);
2651         while (read_next_command() != EOF) {
2652                 if (!strcmp("blob", command_buf.buf))
2653                         parse_new_blob();
2654                 else if (!prefixcmp(command_buf.buf, "commit "))
2655                         parse_new_commit();
2656                 else if (!prefixcmp(command_buf.buf, "tag "))
2657                         parse_new_tag();
2658                 else if (!prefixcmp(command_buf.buf, "reset "))
2659                         parse_reset_branch();
2660                 else if (!strcmp("checkpoint", command_buf.buf))
2661                         parse_checkpoint();
2662                 else if (!prefixcmp(command_buf.buf, "progress "))
2663                         parse_progress();
2664                 else if (!prefixcmp(command_buf.buf, "feature "))
2665                         parse_feature();
2666                 else if (!prefixcmp(command_buf.buf, "option git "))
2667                         parse_option();
2668                 else if (!prefixcmp(command_buf.buf, "option "))
2669                         parse_nongit_option();
2670                 else
2671                         die("Unsupported command: %s", command_buf.buf);
2672         }
2673
2674         /* argv hasn't been parsed yet, do so */
2675         if (!seen_non_option_command)
2676                 parse_argv();
2677
2678         end_packfile();
2679
2680         dump_branches();
2681         dump_tags();
2682         unkeep_all_packs();
2683         dump_marks();
2684
2685         if (pack_edges)
2686                 fclose(pack_edges);
2687
2688         if (show_stats) {
2689                 uintmax_t total_count = 0, duplicate_count = 0;
2690                 for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
2691                         total_count += object_count_by_type[i];
2692                 for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
2693                         duplicate_count += duplicate_count_by_type[i];
2694
2695                 fprintf(stderr, "%s statistics:\n", argv[0]);
2696                 fprintf(stderr, "---------------------------------------------------------------------\n");
2697                 fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
2698                 fprintf(stderr, "Total objects:   %10" PRIuMAX " (%10" PRIuMAX " duplicates                  )\n", total_count, duplicate_count);
2699                 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]);
2700                 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]);
2701                 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]);
2702                 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]);
2703                 fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
2704                 fprintf(stderr, "      marks:     %10" PRIuMAX " (%10" PRIuMAX " unique    )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
2705                 fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
2706                 fprintf(stderr, "Memory total:    %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
2707                 fprintf(stderr, "       pools:    %10lu KiB\n", (unsigned long)(total_allocd/1024));
2708                 fprintf(stderr, "     objects:    %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
2709                 fprintf(stderr, "---------------------------------------------------------------------\n");
2710                 pack_report();
2711                 fprintf(stderr, "---------------------------------------------------------------------\n");
2712                 fprintf(stderr, "\n");
2713         }
2714
2715         return failure ? 1 : 0;
2716 }