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