bbac58cae97b3587af5eb2fdf198f250be8005be
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 commit-ish lf)?
26 ('merge' sp commit-ish lf)*
27 (file_change | ls)*
28 lf?;
29 commit_msg ::= data;
30
31 ls ::= 'ls' sp '"' quoted(path) '"' lf;
32
33 file_change ::= file_clr
34 | file_del
35 | file_rnm
36 | file_cpy
37 | file_obm
38 | file_inm;
39 file_clr ::= 'deleteall' lf;
40 file_del ::= 'D' sp path_str lf;
41 file_rnm ::= 'R' sp path_str sp path_str lf;
42 file_cpy ::= 'C' sp path_str sp path_str lf;
43 file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf;
44 file_inm ::= 'M' sp mode sp 'inline' sp path_str lf
45 data;
46 note_obm ::= 'N' sp (hexsha1 | idnum) sp commit-ish lf;
47 note_inm ::= 'N' sp 'inline' sp commit-ish lf
48 data;
49
50 new_tag ::= 'tag' sp tag_str lf
51 'from' sp commit-ish lf
52 ('tagger' (sp name)? sp '<' email '>' sp when lf)?
53 tag_msg;
54 tag_msg ::= data;
55
56 reset_branch ::= 'reset' sp ref_str lf
57 ('from' sp commit-ish lf)?
58 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 commit-ish ::= (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, get-mark, ls-tree, and cat-blob requests may
138 # appear anywhere in the input, except within a data command. Any
139 # form of the data command always escapes the related input from
140 # comment processing.
141 #
142 # In case it is not clear, the '#' that starts the comment
143 # must be the first character on that line (an lf
144 # preceded it).
145 #
146
147 get_mark ::= 'get-mark' sp idnum lf;
148 cat_blob ::= 'cat-blob' sp (hexsha1 | idnum) lf;
149 ls_tree ::= 'ls' sp (hexsha1 | idnum) sp path_str lf;
150
151 comment ::= '#' not_lf* lf;
152 not_lf ::= # Any byte that is not ASCII newline (LF);
153*/
154
155#include "builtin.h"
156#include "cache.h"
157#include "config.h"
158#include "lockfile.h"
159#include "object.h"
160#include "blob.h"
161#include "tree.h"
162#include "commit.h"
163#include "delta.h"
164#include "pack.h"
165#include "refs.h"
166#include "csum-file.h"
167#include "quote.h"
168#include "dir.h"
169#include "run-command.h"
170#include "packfile.h"
171
172#define PACK_ID_BITS 16
173#define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
174#define DEPTH_BITS 13
175#define MAX_DEPTH ((1<<DEPTH_BITS)-1)
176
177/*
178 * We abuse the setuid bit on directories to mean "do not delta".
179 */
180#define NO_DELTA S_ISUID
181
182struct object_entry {
183 struct pack_idx_entry idx;
184 struct object_entry *next;
185 uint32_t type : TYPE_BITS,
186 pack_id : PACK_ID_BITS,
187 depth : DEPTH_BITS;
188};
189
190struct object_entry_pool {
191 struct object_entry_pool *next_pool;
192 struct object_entry *next_free;
193 struct object_entry *end;
194 struct object_entry entries[FLEX_ARRAY]; /* more */
195};
196
197struct mark_set {
198 union {
199 struct object_entry *marked[1024];
200 struct mark_set *sets[1024];
201 } data;
202 unsigned int shift;
203};
204
205struct last_object {
206 struct strbuf data;
207 off_t offset;
208 unsigned int depth;
209 unsigned no_swap : 1;
210};
211
212struct mp_block {
213 struct mp_block *next_block;
214 char *next_free;
215 char *end;
216 uintmax_t space[FLEX_ARRAY]; /* more */
217};
218
219struct mem_pool {
220 struct mp_block *mp_block;
221
222 /*
223 * The amount of available memory to grow the pool by.
224 * This size does not include the overhead for the mp_block.
225 */
226 size_t block_alloc;
227
228 /* The total amount of memory allocated by the pool. */
229 size_t pool_alloc;
230};
231
232struct atom_str {
233 struct atom_str *next_atom;
234 unsigned short str_len;
235 char str_dat[FLEX_ARRAY]; /* more */
236};
237
238struct tree_content;
239struct tree_entry {
240 struct tree_content *tree;
241 struct atom_str *name;
242 struct tree_entry_ms {
243 uint16_t mode;
244 struct object_id oid;
245 } versions[2];
246};
247
248struct tree_content {
249 unsigned int entry_capacity; /* must match avail_tree_content */
250 unsigned int entry_count;
251 unsigned int delta_depth;
252 struct tree_entry *entries[FLEX_ARRAY]; /* more */
253};
254
255struct avail_tree_content {
256 unsigned int entry_capacity; /* must match tree_content */
257 struct avail_tree_content *next_avail;
258};
259
260struct branch {
261 struct branch *table_next_branch;
262 struct branch *active_next_branch;
263 const char *name;
264 struct tree_entry branch_tree;
265 uintmax_t last_commit;
266 uintmax_t num_notes;
267 unsigned active : 1;
268 unsigned delete : 1;
269 unsigned pack_id : PACK_ID_BITS;
270 struct object_id oid;
271};
272
273struct tag {
274 struct tag *next_tag;
275 const char *name;
276 unsigned int pack_id;
277 struct object_id oid;
278};
279
280struct hash_list {
281 struct hash_list *next;
282 struct object_id oid;
283};
284
285typedef enum {
286 WHENSPEC_RAW = 1,
287 WHENSPEC_RFC2822,
288 WHENSPEC_NOW
289} whenspec_type;
290
291struct recent_command {
292 struct recent_command *prev;
293 struct recent_command *next;
294 char *buf;
295};
296
297/* Configured limits on output */
298static unsigned long max_depth = 50;
299static off_t max_packsize;
300static int unpack_limit = 100;
301static int force_update;
302
303/* Stats and misc. counters */
304static uintmax_t alloc_count;
305static uintmax_t marks_set_count;
306static uintmax_t object_count_by_type[1 << TYPE_BITS];
307static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
308static uintmax_t delta_count_by_type[1 << TYPE_BITS];
309static uintmax_t delta_count_attempts_by_type[1 << TYPE_BITS];
310static unsigned long object_count;
311static unsigned long branch_count;
312static unsigned long branch_load_count;
313static int failure;
314static FILE *pack_edges;
315static unsigned int show_stats = 1;
316static int global_argc;
317static const char **global_argv;
318
319/* Memory pools */
320static struct mem_pool fi_mem_pool = {0, 2*1024*1024 - sizeof(struct mp_block), 0 };
321
322/* Atom management */
323static unsigned int atom_table_sz = 4451;
324static unsigned int atom_cnt;
325static struct atom_str **atom_table;
326
327/* The .pack file being generated */
328static struct pack_idx_option pack_idx_opts;
329static unsigned int pack_id;
330static struct hashfile *pack_file;
331static struct packed_git *pack_data;
332static struct packed_git **all_packs;
333static off_t pack_size;
334
335/* Table of objects we've written. */
336static unsigned int object_entry_alloc = 5000;
337static struct object_entry_pool *blocks;
338static size_t total_allocd;
339static struct object_entry *object_table[1 << 16];
340static struct mark_set *marks;
341static const char *export_marks_file;
342static const char *import_marks_file;
343static int import_marks_file_from_stream;
344static int import_marks_file_ignore_missing;
345static int import_marks_file_done;
346static int relative_marks_paths;
347
348/* Our last blob */
349static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
350
351/* Tree management */
352static unsigned int tree_entry_alloc = 1000;
353static void *avail_tree_entry;
354static unsigned int avail_tree_table_sz = 100;
355static struct avail_tree_content **avail_tree_table;
356static struct strbuf old_tree = STRBUF_INIT;
357static struct strbuf new_tree = STRBUF_INIT;
358
359/* Branch data */
360static unsigned long max_active_branches = 5;
361static unsigned long cur_active_branches;
362static unsigned long branch_table_sz = 1039;
363static struct branch **branch_table;
364static struct branch *active_branches;
365
366/* Tag data */
367static struct tag *first_tag;
368static struct tag *last_tag;
369
370/* Input stream parsing */
371static whenspec_type whenspec = WHENSPEC_RAW;
372static struct strbuf command_buf = STRBUF_INIT;
373static int unread_command_buf;
374static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
375static struct recent_command *cmd_tail = &cmd_hist;
376static struct recent_command *rc_free;
377static unsigned int cmd_save = 100;
378static uintmax_t next_mark;
379static struct strbuf new_data = STRBUF_INIT;
380static int seen_data_command;
381static int require_explicit_termination;
382
383/* Signal handling */
384static volatile sig_atomic_t checkpoint_requested;
385
386/* Where to write output of cat-blob commands */
387static int cat_blob_fd = STDOUT_FILENO;
388
389static void parse_argv(void);
390static void parse_get_mark(const char *p);
391static void parse_cat_blob(const char *p);
392static void parse_ls(const char *p, struct branch *b);
393
394static void write_branch_report(FILE *rpt, struct branch *b)
395{
396 fprintf(rpt, "%s:\n", b->name);
397
398 fprintf(rpt, " status :");
399 if (b->active)
400 fputs(" active", rpt);
401 if (b->branch_tree.tree)
402 fputs(" loaded", rpt);
403 if (is_null_oid(&b->branch_tree.versions[1].oid))
404 fputs(" dirty", rpt);
405 fputc('\n', rpt);
406
407 fprintf(rpt, " tip commit : %s\n", oid_to_hex(&b->oid));
408 fprintf(rpt, " old tree : %s\n",
409 oid_to_hex(&b->branch_tree.versions[0].oid));
410 fprintf(rpt, " cur tree : %s\n",
411 oid_to_hex(&b->branch_tree.versions[1].oid));
412 fprintf(rpt, " commit clock: %" PRIuMAX "\n", b->last_commit);
413
414 fputs(" last pack : ", rpt);
415 if (b->pack_id < MAX_PACK_ID)
416 fprintf(rpt, "%u", b->pack_id);
417 fputc('\n', rpt);
418
419 fputc('\n', rpt);
420}
421
422static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *);
423
424static void write_crash_report(const char *err)
425{
426 char *loc = git_pathdup("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
427 FILE *rpt = fopen(loc, "w");
428 struct branch *b;
429 unsigned long lu;
430 struct recent_command *rc;
431
432 if (!rpt) {
433 error_errno("can't write crash report %s", loc);
434 free(loc);
435 return;
436 }
437
438 fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
439
440 fprintf(rpt, "fast-import crash report:\n");
441 fprintf(rpt, " fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
442 fprintf(rpt, " parent process : %"PRIuMAX"\n", (uintmax_t) getppid());
443 fprintf(rpt, " at %s\n", show_date(time(NULL), 0, DATE_MODE(ISO8601)));
444 fputc('\n', rpt);
445
446 fputs("fatal: ", rpt);
447 fputs(err, rpt);
448 fputc('\n', rpt);
449
450 fputc('\n', rpt);
451 fputs("Most Recent Commands Before Crash\n", rpt);
452 fputs("---------------------------------\n", rpt);
453 for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
454 if (rc->next == &cmd_hist)
455 fputs("* ", rpt);
456 else
457 fputs(" ", rpt);
458 fputs(rc->buf, rpt);
459 fputc('\n', rpt);
460 }
461
462 fputc('\n', rpt);
463 fputs("Active Branch LRU\n", rpt);
464 fputs("-----------------\n", rpt);
465 fprintf(rpt, " active_branches = %lu cur, %lu max\n",
466 cur_active_branches,
467 max_active_branches);
468 fputc('\n', rpt);
469 fputs(" pos clock name\n", rpt);
470 fputs(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
471 for (b = active_branches, lu = 0; b; b = b->active_next_branch)
472 fprintf(rpt, " %2lu) %6" PRIuMAX" %s\n",
473 ++lu, b->last_commit, b->name);
474
475 fputc('\n', rpt);
476 fputs("Inactive Branches\n", rpt);
477 fputs("-----------------\n", rpt);
478 for (lu = 0; lu < branch_table_sz; lu++) {
479 for (b = branch_table[lu]; b; b = b->table_next_branch)
480 write_branch_report(rpt, b);
481 }
482
483 if (first_tag) {
484 struct tag *tg;
485 fputc('\n', rpt);
486 fputs("Annotated Tags\n", rpt);
487 fputs("--------------\n", rpt);
488 for (tg = first_tag; tg; tg = tg->next_tag) {
489 fputs(oid_to_hex(&tg->oid), rpt);
490 fputc(' ', rpt);
491 fputs(tg->name, rpt);
492 fputc('\n', rpt);
493 }
494 }
495
496 fputc('\n', rpt);
497 fputs("Marks\n", rpt);
498 fputs("-----\n", rpt);
499 if (export_marks_file)
500 fprintf(rpt, " exported to %s\n", export_marks_file);
501 else
502 dump_marks_helper(rpt, 0, marks);
503
504 fputc('\n', rpt);
505 fputs("-------------------\n", rpt);
506 fputs("END OF CRASH REPORT\n", rpt);
507 fclose(rpt);
508 free(loc);
509}
510
511static void end_packfile(void);
512static void unkeep_all_packs(void);
513static void dump_marks(void);
514
515static NORETURN void die_nicely(const char *err, va_list params)
516{
517 static int zombie;
518 char message[2 * PATH_MAX];
519
520 vsnprintf(message, sizeof(message), err, params);
521 fputs("fatal: ", stderr);
522 fputs(message, stderr);
523 fputc('\n', stderr);
524
525 if (!zombie) {
526 zombie = 1;
527 write_crash_report(message);
528 end_packfile();
529 unkeep_all_packs();
530 dump_marks();
531 }
532 exit(128);
533}
534
535#ifndef SIGUSR1 /* Windows, for example */
536
537static void set_checkpoint_signal(void)
538{
539}
540
541#else
542
543static void checkpoint_signal(int signo)
544{
545 checkpoint_requested = 1;
546}
547
548static void set_checkpoint_signal(void)
549{
550 struct sigaction sa;
551
552 memset(&sa, 0, sizeof(sa));
553 sa.sa_handler = checkpoint_signal;
554 sigemptyset(&sa.sa_mask);
555 sa.sa_flags = SA_RESTART;
556 sigaction(SIGUSR1, &sa, NULL);
557}
558
559#endif
560
561static void alloc_objects(unsigned int cnt)
562{
563 struct object_entry_pool *b;
564
565 b = xmalloc(sizeof(struct object_entry_pool)
566 + cnt * sizeof(struct object_entry));
567 b->next_pool = blocks;
568 b->next_free = b->entries;
569 b->end = b->entries + cnt;
570 blocks = b;
571 alloc_count += cnt;
572}
573
574static struct object_entry *new_object(struct object_id *oid)
575{
576 struct object_entry *e;
577
578 if (blocks->next_free == blocks->end)
579 alloc_objects(object_entry_alloc);
580
581 e = blocks->next_free++;
582 oidcpy(&e->idx.oid, oid);
583 return e;
584}
585
586static struct object_entry *find_object(struct object_id *oid)
587{
588 unsigned int h = oid->hash[0] << 8 | oid->hash[1];
589 struct object_entry *e;
590 for (e = object_table[h]; e; e = e->next)
591 if (!oidcmp(oid, &e->idx.oid))
592 return e;
593 return NULL;
594}
595
596static struct object_entry *insert_object(struct object_id *oid)
597{
598 unsigned int h = oid->hash[0] << 8 | oid->hash[1];
599 struct object_entry *e = object_table[h];
600
601 while (e) {
602 if (!oidcmp(oid, &e->idx.oid))
603 return e;
604 e = e->next;
605 }
606
607 e = new_object(oid);
608 e->next = object_table[h];
609 e->idx.offset = 0;
610 object_table[h] = e;
611 return e;
612}
613
614static void invalidate_pack_id(unsigned int id)
615{
616 unsigned int h;
617 unsigned long lu;
618 struct tag *t;
619
620 for (h = 0; h < ARRAY_SIZE(object_table); h++) {
621 struct object_entry *e;
622
623 for (e = object_table[h]; e; e = e->next)
624 if (e->pack_id == id)
625 e->pack_id = MAX_PACK_ID;
626 }
627
628 for (lu = 0; lu < branch_table_sz; lu++) {
629 struct branch *b;
630
631 for (b = branch_table[lu]; b; b = b->table_next_branch)
632 if (b->pack_id == id)
633 b->pack_id = MAX_PACK_ID;
634 }
635
636 for (t = first_tag; t; t = t->next_tag)
637 if (t->pack_id == id)
638 t->pack_id = MAX_PACK_ID;
639}
640
641static unsigned int hc_str(const char *s, size_t len)
642{
643 unsigned int r = 0;
644 while (len-- > 0)
645 r = r * 31 + *s++;
646 return r;
647}
648
649static struct mp_block *mem_pool_alloc_block(struct mem_pool *mem_pool, size_t block_alloc)
650{
651 struct mp_block *p;
652
653 mem_pool->pool_alloc += sizeof(struct mp_block) + block_alloc;
654 p = xmalloc(st_add(sizeof(struct mp_block), block_alloc));
655 p->next_block = mem_pool->mp_block;
656 p->next_free = (char *)p->space;
657 p->end = p->next_free + block_alloc;
658 mem_pool->mp_block = p;
659
660 return p;
661}
662
663static void *mem_pool_alloc(struct mem_pool *mem_pool, size_t len)
664{
665 struct mp_block *p;
666 void *r;
667
668 /* round up to a 'uintmax_t' alignment */
669 if (len & (sizeof(uintmax_t) - 1))
670 len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
671
672 for (p = mem_pool->mp_block; p; p = p->next_block)
673 if (p->end - p->next_free >= len)
674 break;
675
676 if (!p) {
677 if (len >= (mem_pool->block_alloc / 2)) {
678 mem_pool->pool_alloc += len;
679 return xmalloc(len);
680 }
681
682 p = mem_pool_alloc_block(mem_pool, mem_pool->block_alloc);
683 }
684
685 r = p->next_free;
686 p->next_free += len;
687 return r;
688}
689
690static void *mem_pool_calloc(struct mem_pool *mem_pool, size_t count, size_t size)
691{
692 size_t len = st_mult(count, size);
693 void *r = mem_pool_alloc(mem_pool, len);
694 memset(r, 0, len);
695 return r;
696}
697
698static char *pool_strdup(const char *s)
699{
700 size_t len = strlen(s) + 1;
701 char *r = mem_pool_alloc(&fi_mem_pool, len);
702 memcpy(r, s, len);
703 return r;
704}
705
706static void insert_mark(uintmax_t idnum, struct object_entry *oe)
707{
708 struct mark_set *s = marks;
709 while ((idnum >> s->shift) >= 1024) {
710 s = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
711 s->shift = marks->shift + 10;
712 s->data.sets[0] = marks;
713 marks = s;
714 }
715 while (s->shift) {
716 uintmax_t i = idnum >> s->shift;
717 idnum -= i << s->shift;
718 if (!s->data.sets[i]) {
719 s->data.sets[i] = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
720 s->data.sets[i]->shift = s->shift - 10;
721 }
722 s = s->data.sets[i];
723 }
724 if (!s->data.marked[idnum])
725 marks_set_count++;
726 s->data.marked[idnum] = oe;
727}
728
729static struct object_entry *find_mark(uintmax_t idnum)
730{
731 uintmax_t orig_idnum = idnum;
732 struct mark_set *s = marks;
733 struct object_entry *oe = NULL;
734 if ((idnum >> s->shift) < 1024) {
735 while (s && s->shift) {
736 uintmax_t i = idnum >> s->shift;
737 idnum -= i << s->shift;
738 s = s->data.sets[i];
739 }
740 if (s)
741 oe = s->data.marked[idnum];
742 }
743 if (!oe)
744 die("mark :%" PRIuMAX " not declared", orig_idnum);
745 return oe;
746}
747
748static struct atom_str *to_atom(const char *s, unsigned short len)
749{
750 unsigned int hc = hc_str(s, len) % atom_table_sz;
751 struct atom_str *c;
752
753 for (c = atom_table[hc]; c; c = c->next_atom)
754 if (c->str_len == len && !strncmp(s, c->str_dat, len))
755 return c;
756
757 c = mem_pool_alloc(&fi_mem_pool, sizeof(struct atom_str) + len + 1);
758 c->str_len = len;
759 memcpy(c->str_dat, s, len);
760 c->str_dat[len] = 0;
761 c->next_atom = atom_table[hc];
762 atom_table[hc] = c;
763 atom_cnt++;
764 return c;
765}
766
767static struct branch *lookup_branch(const char *name)
768{
769 unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
770 struct branch *b;
771
772 for (b = branch_table[hc]; b; b = b->table_next_branch)
773 if (!strcmp(name, b->name))
774 return b;
775 return NULL;
776}
777
778static struct branch *new_branch(const char *name)
779{
780 unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
781 struct branch *b = lookup_branch(name);
782
783 if (b)
784 die("Invalid attempt to create duplicate branch: %s", name);
785 if (check_refname_format(name, REFNAME_ALLOW_ONELEVEL))
786 die("Branch name doesn't conform to GIT standards: %s", name);
787
788 b = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct branch));
789 b->name = pool_strdup(name);
790 b->table_next_branch = branch_table[hc];
791 b->branch_tree.versions[0].mode = S_IFDIR;
792 b->branch_tree.versions[1].mode = S_IFDIR;
793 b->num_notes = 0;
794 b->active = 0;
795 b->pack_id = MAX_PACK_ID;
796 branch_table[hc] = b;
797 branch_count++;
798 return b;
799}
800
801static unsigned int hc_entries(unsigned int cnt)
802{
803 cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
804 return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
805}
806
807static struct tree_content *new_tree_content(unsigned int cnt)
808{
809 struct avail_tree_content *f, *l = NULL;
810 struct tree_content *t;
811 unsigned int hc = hc_entries(cnt);
812
813 for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
814 if (f->entry_capacity >= cnt)
815 break;
816
817 if (f) {
818 if (l)
819 l->next_avail = f->next_avail;
820 else
821 avail_tree_table[hc] = f->next_avail;
822 } else {
823 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
824 f = mem_pool_alloc(&fi_mem_pool, sizeof(*t) + sizeof(t->entries[0]) * cnt);
825 f->entry_capacity = cnt;
826 }
827
828 t = (struct tree_content*)f;
829 t->entry_count = 0;
830 t->delta_depth = 0;
831 return t;
832}
833
834static void release_tree_entry(struct tree_entry *e);
835static void release_tree_content(struct tree_content *t)
836{
837 struct avail_tree_content *f = (struct avail_tree_content*)t;
838 unsigned int hc = hc_entries(f->entry_capacity);
839 f->next_avail = avail_tree_table[hc];
840 avail_tree_table[hc] = f;
841}
842
843static void release_tree_content_recursive(struct tree_content *t)
844{
845 unsigned int i;
846 for (i = 0; i < t->entry_count; i++)
847 release_tree_entry(t->entries[i]);
848 release_tree_content(t);
849}
850
851static struct tree_content *grow_tree_content(
852 struct tree_content *t,
853 int amt)
854{
855 struct tree_content *r = new_tree_content(t->entry_count + amt);
856 r->entry_count = t->entry_count;
857 r->delta_depth = t->delta_depth;
858 memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
859 release_tree_content(t);
860 return r;
861}
862
863static struct tree_entry *new_tree_entry(void)
864{
865 struct tree_entry *e;
866
867 if (!avail_tree_entry) {
868 unsigned int n = tree_entry_alloc;
869 total_allocd += n * sizeof(struct tree_entry);
870 ALLOC_ARRAY(e, n);
871 avail_tree_entry = e;
872 while (n-- > 1) {
873 *((void**)e) = e + 1;
874 e++;
875 }
876 *((void**)e) = NULL;
877 }
878
879 e = avail_tree_entry;
880 avail_tree_entry = *((void**)e);
881 return e;
882}
883
884static void release_tree_entry(struct tree_entry *e)
885{
886 if (e->tree)
887 release_tree_content_recursive(e->tree);
888 *((void**)e) = avail_tree_entry;
889 avail_tree_entry = e;
890}
891
892static struct tree_content *dup_tree_content(struct tree_content *s)
893{
894 struct tree_content *d;
895 struct tree_entry *a, *b;
896 unsigned int i;
897
898 if (!s)
899 return NULL;
900 d = new_tree_content(s->entry_count);
901 for (i = 0; i < s->entry_count; i++) {
902 a = s->entries[i];
903 b = new_tree_entry();
904 memcpy(b, a, sizeof(*a));
905 if (a->tree && is_null_oid(&b->versions[1].oid))
906 b->tree = dup_tree_content(a->tree);
907 else
908 b->tree = NULL;
909 d->entries[i] = b;
910 }
911 d->entry_count = s->entry_count;
912 d->delta_depth = s->delta_depth;
913
914 return d;
915}
916
917static void start_packfile(void)
918{
919 struct strbuf tmp_file = STRBUF_INIT;
920 struct packed_git *p;
921 struct pack_header hdr;
922 int pack_fd;
923
924 pack_fd = odb_mkstemp(&tmp_file, "pack/tmp_pack_XXXXXX");
925 FLEX_ALLOC_STR(p, pack_name, tmp_file.buf);
926 strbuf_release(&tmp_file);
927
928 p->pack_fd = pack_fd;
929 p->do_not_close = 1;
930 pack_file = hashfd(pack_fd, p->pack_name);
931
932 hdr.hdr_signature = htonl(PACK_SIGNATURE);
933 hdr.hdr_version = htonl(2);
934 hdr.hdr_entries = 0;
935 hashwrite(pack_file, &hdr, sizeof(hdr));
936
937 pack_data = p;
938 pack_size = sizeof(hdr);
939 object_count = 0;
940
941 REALLOC_ARRAY(all_packs, pack_id + 1);
942 all_packs[pack_id] = p;
943}
944
945static const char *create_index(void)
946{
947 const char *tmpfile;
948 struct pack_idx_entry **idx, **c, **last;
949 struct object_entry *e;
950 struct object_entry_pool *o;
951
952 /* Build the table of object IDs. */
953 ALLOC_ARRAY(idx, object_count);
954 c = idx;
955 for (o = blocks; o; o = o->next_pool)
956 for (e = o->next_free; e-- != o->entries;)
957 if (pack_id == e->pack_id)
958 *c++ = &e->idx;
959 last = idx + object_count;
960 if (c != last)
961 die("internal consistency error creating the index");
962
963 tmpfile = write_idx_file(NULL, idx, object_count, &pack_idx_opts, pack_data->sha1);
964 free(idx);
965 return tmpfile;
966}
967
968static char *keep_pack(const char *curr_index_name)
969{
970 static const char *keep_msg = "fast-import";
971 struct strbuf name = STRBUF_INIT;
972 int keep_fd;
973
974 odb_pack_name(&name, pack_data->sha1, "keep");
975 keep_fd = odb_pack_keep(name.buf);
976 if (keep_fd < 0)
977 die_errno("cannot create keep file");
978 write_or_die(keep_fd, keep_msg, strlen(keep_msg));
979 if (close(keep_fd))
980 die_errno("failed to write keep file");
981
982 odb_pack_name(&name, pack_data->sha1, "pack");
983 if (finalize_object_file(pack_data->pack_name, name.buf))
984 die("cannot store pack file");
985
986 odb_pack_name(&name, pack_data->sha1, "idx");
987 if (finalize_object_file(curr_index_name, name.buf))
988 die("cannot store index file");
989 free((void *)curr_index_name);
990 return strbuf_detach(&name, NULL);
991}
992
993static void unkeep_all_packs(void)
994{
995 struct strbuf name = STRBUF_INIT;
996 int k;
997
998 for (k = 0; k < pack_id; k++) {
999 struct packed_git *p = all_packs[k];
1000 odb_pack_name(&name, p->sha1, "keep");
1001 unlink_or_warn(name.buf);
1002 }
1003 strbuf_release(&name);
1004}
1005
1006static int loosen_small_pack(const struct packed_git *p)
1007{
1008 struct child_process unpack = CHILD_PROCESS_INIT;
1009
1010 if (lseek(p->pack_fd, 0, SEEK_SET) < 0)
1011 die_errno("Failed seeking to start of '%s'", p->pack_name);
1012
1013 unpack.in = p->pack_fd;
1014 unpack.git_cmd = 1;
1015 unpack.stdout_to_stderr = 1;
1016 argv_array_push(&unpack.args, "unpack-objects");
1017 if (!show_stats)
1018 argv_array_push(&unpack.args, "-q");
1019
1020 return run_command(&unpack);
1021}
1022
1023static void end_packfile(void)
1024{
1025 static int running;
1026
1027 if (running || !pack_data)
1028 return;
1029
1030 running = 1;
1031 clear_delta_base_cache();
1032 if (object_count) {
1033 struct packed_git *new_p;
1034 struct object_id cur_pack_oid;
1035 char *idx_name;
1036 int i;
1037 struct branch *b;
1038 struct tag *t;
1039
1040 close_pack_windows(pack_data);
1041 hashclose(pack_file, cur_pack_oid.hash, 0);
1042 fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
1043 pack_data->pack_name, object_count,
1044 cur_pack_oid.hash, pack_size);
1045
1046 if (object_count <= unpack_limit) {
1047 if (!loosen_small_pack(pack_data)) {
1048 invalidate_pack_id(pack_id);
1049 goto discard_pack;
1050 }
1051 }
1052
1053 close(pack_data->pack_fd);
1054 idx_name = keep_pack(create_index());
1055
1056 /* Register the packfile with core git's machinery. */
1057 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
1058 if (!new_p)
1059 die("core git rejected index %s", idx_name);
1060 all_packs[pack_id] = new_p;
1061 install_packed_git(new_p);
1062 free(idx_name);
1063
1064 /* Print the boundary */
1065 if (pack_edges) {
1066 fprintf(pack_edges, "%s:", new_p->pack_name);
1067 for (i = 0; i < branch_table_sz; i++) {
1068 for (b = branch_table[i]; b; b = b->table_next_branch) {
1069 if (b->pack_id == pack_id)
1070 fprintf(pack_edges, " %s",
1071 oid_to_hex(&b->oid));
1072 }
1073 }
1074 for (t = first_tag; t; t = t->next_tag) {
1075 if (t->pack_id == pack_id)
1076 fprintf(pack_edges, " %s",
1077 oid_to_hex(&t->oid));
1078 }
1079 fputc('\n', pack_edges);
1080 fflush(pack_edges);
1081 }
1082
1083 pack_id++;
1084 }
1085 else {
1086discard_pack:
1087 close(pack_data->pack_fd);
1088 unlink_or_warn(pack_data->pack_name);
1089 }
1090 FREE_AND_NULL(pack_data);
1091 running = 0;
1092
1093 /* We can't carry a delta across packfiles. */
1094 strbuf_release(&last_blob.data);
1095 last_blob.offset = 0;
1096 last_blob.depth = 0;
1097}
1098
1099static void cycle_packfile(void)
1100{
1101 end_packfile();
1102 start_packfile();
1103}
1104
1105static int store_object(
1106 enum object_type type,
1107 struct strbuf *dat,
1108 struct last_object *last,
1109 struct object_id *oidout,
1110 uintmax_t mark)
1111{
1112 void *out, *delta;
1113 struct object_entry *e;
1114 unsigned char hdr[96];
1115 struct object_id oid;
1116 unsigned long hdrlen, deltalen;
1117 git_hash_ctx c;
1118 git_zstream s;
1119
1120 hdrlen = xsnprintf((char *)hdr, sizeof(hdr), "%s %lu",
1121 type_name(type), (unsigned long)dat->len) + 1;
1122 the_hash_algo->init_fn(&c);
1123 the_hash_algo->update_fn(&c, hdr, hdrlen);
1124 the_hash_algo->update_fn(&c, dat->buf, dat->len);
1125 the_hash_algo->final_fn(oid.hash, &c);
1126 if (oidout)
1127 oidcpy(oidout, &oid);
1128
1129 e = insert_object(&oid);
1130 if (mark)
1131 insert_mark(mark, e);
1132 if (e->idx.offset) {
1133 duplicate_count_by_type[type]++;
1134 return 1;
1135 } else if (find_sha1_pack(oid.hash, packed_git)) {
1136 e->type = type;
1137 e->pack_id = MAX_PACK_ID;
1138 e->idx.offset = 1; /* just not zero! */
1139 duplicate_count_by_type[type]++;
1140 return 1;
1141 }
1142
1143 if (last && last->data.buf && last->depth < max_depth
1144 && dat->len > the_hash_algo->rawsz) {
1145
1146 delta_count_attempts_by_type[type]++;
1147 delta = diff_delta(last->data.buf, last->data.len,
1148 dat->buf, dat->len,
1149 &deltalen, dat->len - the_hash_algo->rawsz);
1150 } else
1151 delta = NULL;
1152
1153 git_deflate_init(&s, pack_compression_level);
1154 if (delta) {
1155 s.next_in = delta;
1156 s.avail_in = deltalen;
1157 } else {
1158 s.next_in = (void *)dat->buf;
1159 s.avail_in = dat->len;
1160 }
1161 s.avail_out = git_deflate_bound(&s, s.avail_in);
1162 s.next_out = out = xmalloc(s.avail_out);
1163 while (git_deflate(&s, Z_FINISH) == Z_OK)
1164 ; /* nothing */
1165 git_deflate_end(&s);
1166
1167 /* Determine if we should auto-checkpoint. */
1168 if ((max_packsize && (pack_size + 60 + s.total_out) > max_packsize)
1169 || (pack_size + 60 + s.total_out) < pack_size) {
1170
1171 /* This new object needs to *not* have the current pack_id. */
1172 e->pack_id = pack_id + 1;
1173 cycle_packfile();
1174
1175 /* We cannot carry a delta into the new pack. */
1176 if (delta) {
1177 FREE_AND_NULL(delta);
1178
1179 git_deflate_init(&s, pack_compression_level);
1180 s.next_in = (void *)dat->buf;
1181 s.avail_in = dat->len;
1182 s.avail_out = git_deflate_bound(&s, s.avail_in);
1183 s.next_out = out = xrealloc(out, s.avail_out);
1184 while (git_deflate(&s, Z_FINISH) == Z_OK)
1185 ; /* nothing */
1186 git_deflate_end(&s);
1187 }
1188 }
1189
1190 e->type = type;
1191 e->pack_id = pack_id;
1192 e->idx.offset = pack_size;
1193 object_count++;
1194 object_count_by_type[type]++;
1195
1196 crc32_begin(pack_file);
1197
1198 if (delta) {
1199 off_t ofs = e->idx.offset - last->offset;
1200 unsigned pos = sizeof(hdr) - 1;
1201
1202 delta_count_by_type[type]++;
1203 e->depth = last->depth + 1;
1204
1205 hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1206 OBJ_OFS_DELTA, deltalen);
1207 hashwrite(pack_file, hdr, hdrlen);
1208 pack_size += hdrlen;
1209
1210 hdr[pos] = ofs & 127;
1211 while (ofs >>= 7)
1212 hdr[--pos] = 128 | (--ofs & 127);
1213 hashwrite(pack_file, hdr + pos, sizeof(hdr) - pos);
1214 pack_size += sizeof(hdr) - pos;
1215 } else {
1216 e->depth = 0;
1217 hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1218 type, dat->len);
1219 hashwrite(pack_file, hdr, hdrlen);
1220 pack_size += hdrlen;
1221 }
1222
1223 hashwrite(pack_file, out, s.total_out);
1224 pack_size += s.total_out;
1225
1226 e->idx.crc32 = crc32_end(pack_file);
1227
1228 free(out);
1229 free(delta);
1230 if (last) {
1231 if (last->no_swap) {
1232 last->data = *dat;
1233 } else {
1234 strbuf_swap(&last->data, dat);
1235 }
1236 last->offset = e->idx.offset;
1237 last->depth = e->depth;
1238 }
1239 return 0;
1240}
1241
1242static void truncate_pack(struct hashfile_checkpoint *checkpoint)
1243{
1244 if (hashfile_truncate(pack_file, checkpoint))
1245 die_errno("cannot truncate pack to skip duplicate");
1246 pack_size = checkpoint->offset;
1247}
1248
1249static void stream_blob(uintmax_t len, struct object_id *oidout, uintmax_t mark)
1250{
1251 size_t in_sz = 64 * 1024, out_sz = 64 * 1024;
1252 unsigned char *in_buf = xmalloc(in_sz);
1253 unsigned char *out_buf = xmalloc(out_sz);
1254 struct object_entry *e;
1255 struct object_id oid;
1256 unsigned long hdrlen;
1257 off_t offset;
1258 git_hash_ctx c;
1259 git_zstream s;
1260 struct hashfile_checkpoint checkpoint;
1261 int status = Z_OK;
1262
1263 /* Determine if we should auto-checkpoint. */
1264 if ((max_packsize && (pack_size + 60 + len) > max_packsize)
1265 || (pack_size + 60 + len) < pack_size)
1266 cycle_packfile();
1267
1268 hashfile_checkpoint(pack_file, &checkpoint);
1269 offset = checkpoint.offset;
1270
1271 hdrlen = xsnprintf((char *)out_buf, out_sz, "blob %" PRIuMAX, len) + 1;
1272
1273 the_hash_algo->init_fn(&c);
1274 the_hash_algo->update_fn(&c, out_buf, hdrlen);
1275
1276 crc32_begin(pack_file);
1277
1278 git_deflate_init(&s, pack_compression_level);
1279
1280 hdrlen = encode_in_pack_object_header(out_buf, out_sz, OBJ_BLOB, len);
1281
1282 s.next_out = out_buf + hdrlen;
1283 s.avail_out = out_sz - hdrlen;
1284
1285 while (status != Z_STREAM_END) {
1286 if (0 < len && !s.avail_in) {
1287 size_t cnt = in_sz < len ? in_sz : (size_t)len;
1288 size_t n = fread(in_buf, 1, cnt, stdin);
1289 if (!n && feof(stdin))
1290 die("EOF in data (%" PRIuMAX " bytes remaining)", len);
1291
1292 the_hash_algo->update_fn(&c, in_buf, n);
1293 s.next_in = in_buf;
1294 s.avail_in = n;
1295 len -= n;
1296 }
1297
1298 status = git_deflate(&s, len ? 0 : Z_FINISH);
1299
1300 if (!s.avail_out || status == Z_STREAM_END) {
1301 size_t n = s.next_out - out_buf;
1302 hashwrite(pack_file, out_buf, n);
1303 pack_size += n;
1304 s.next_out = out_buf;
1305 s.avail_out = out_sz;
1306 }
1307
1308 switch (status) {
1309 case Z_OK:
1310 case Z_BUF_ERROR:
1311 case Z_STREAM_END:
1312 continue;
1313 default:
1314 die("unexpected deflate failure: %d", status);
1315 }
1316 }
1317 git_deflate_end(&s);
1318 the_hash_algo->final_fn(oid.hash, &c);
1319
1320 if (oidout)
1321 oidcpy(oidout, &oid);
1322
1323 e = insert_object(&oid);
1324
1325 if (mark)
1326 insert_mark(mark, e);
1327
1328 if (e->idx.offset) {
1329 duplicate_count_by_type[OBJ_BLOB]++;
1330 truncate_pack(&checkpoint);
1331
1332 } else if (find_sha1_pack(oid.hash, packed_git)) {
1333 e->type = OBJ_BLOB;
1334 e->pack_id = MAX_PACK_ID;
1335 e->idx.offset = 1; /* just not zero! */
1336 duplicate_count_by_type[OBJ_BLOB]++;
1337 truncate_pack(&checkpoint);
1338
1339 } else {
1340 e->depth = 0;
1341 e->type = OBJ_BLOB;
1342 e->pack_id = pack_id;
1343 e->idx.offset = offset;
1344 e->idx.crc32 = crc32_end(pack_file);
1345 object_count++;
1346 object_count_by_type[OBJ_BLOB]++;
1347 }
1348
1349 free(in_buf);
1350 free(out_buf);
1351}
1352
1353/* All calls must be guarded by find_object() or find_mark() to
1354 * ensure the 'struct object_entry' passed was written by this
1355 * process instance. We unpack the entry by the offset, avoiding
1356 * the need for the corresponding .idx file. This unpacking rule
1357 * works because we only use OBJ_REF_DELTA within the packfiles
1358 * created by fast-import.
1359 *
1360 * oe must not be NULL. Such an oe usually comes from giving
1361 * an unknown SHA-1 to find_object() or an undefined mark to
1362 * find_mark(). Callers must test for this condition and use
1363 * the standard read_sha1_file() when it happens.
1364 *
1365 * oe->pack_id must not be MAX_PACK_ID. Such an oe is usually from
1366 * find_mark(), where the mark was reloaded from an existing marks
1367 * file and is referencing an object that this fast-import process
1368 * instance did not write out to a packfile. Callers must test for
1369 * this condition and use read_sha1_file() instead.
1370 */
1371static void *gfi_unpack_entry(
1372 struct object_entry *oe,
1373 unsigned long *sizep)
1374{
1375 enum object_type type;
1376 struct packed_git *p = all_packs[oe->pack_id];
1377 if (p == pack_data && p->pack_size < (pack_size + the_hash_algo->rawsz)) {
1378 /* The object is stored in the packfile we are writing to
1379 * and we have modified it since the last time we scanned
1380 * back to read a previously written object. If an old
1381 * window covered [p->pack_size, p->pack_size + rawsz) its
1382 * data is stale and is not valid. Closing all windows
1383 * and updating the packfile length ensures we can read
1384 * the newly written data.
1385 */
1386 close_pack_windows(p);
1387 hashflush(pack_file);
1388
1389 /* We have to offer rawsz bytes additional on the end of
1390 * the packfile as the core unpacker code assumes the
1391 * footer is present at the file end and must promise
1392 * at least rawsz bytes within any window it maps. But
1393 * we don't actually create the footer here.
1394 */
1395 p->pack_size = pack_size + the_hash_algo->rawsz;
1396 }
1397 return unpack_entry(p, oe->idx.offset, &type, sizep);
1398}
1399
1400static const char *get_mode(const char *str, uint16_t *modep)
1401{
1402 unsigned char c;
1403 uint16_t mode = 0;
1404
1405 while ((c = *str++) != ' ') {
1406 if (c < '0' || c > '7')
1407 return NULL;
1408 mode = (mode << 3) + (c - '0');
1409 }
1410 *modep = mode;
1411 return str;
1412}
1413
1414static void load_tree(struct tree_entry *root)
1415{
1416 struct object_id *oid = &root->versions[1].oid;
1417 struct object_entry *myoe;
1418 struct tree_content *t;
1419 unsigned long size;
1420 char *buf;
1421 const char *c;
1422
1423 root->tree = t = new_tree_content(8);
1424 if (is_null_oid(oid))
1425 return;
1426
1427 myoe = find_object(oid);
1428 if (myoe && myoe->pack_id != MAX_PACK_ID) {
1429 if (myoe->type != OBJ_TREE)
1430 die("Not a tree: %s", oid_to_hex(oid));
1431 t->delta_depth = myoe->depth;
1432 buf = gfi_unpack_entry(myoe, &size);
1433 if (!buf)
1434 die("Can't load tree %s", oid_to_hex(oid));
1435 } else {
1436 enum object_type type;
1437 buf = read_sha1_file(oid->hash, &type, &size);
1438 if (!buf || type != OBJ_TREE)
1439 die("Can't load tree %s", oid_to_hex(oid));
1440 }
1441
1442 c = buf;
1443 while (c != (buf + size)) {
1444 struct tree_entry *e = new_tree_entry();
1445
1446 if (t->entry_count == t->entry_capacity)
1447 root->tree = t = grow_tree_content(t, t->entry_count);
1448 t->entries[t->entry_count++] = e;
1449
1450 e->tree = NULL;
1451 c = get_mode(c, &e->versions[1].mode);
1452 if (!c)
1453 die("Corrupt mode in %s", oid_to_hex(oid));
1454 e->versions[0].mode = e->versions[1].mode;
1455 e->name = to_atom(c, strlen(c));
1456 c += e->name->str_len + 1;
1457 hashcpy(e->versions[0].oid.hash, (unsigned char *)c);
1458 hashcpy(e->versions[1].oid.hash, (unsigned char *)c);
1459 c += GIT_SHA1_RAWSZ;
1460 }
1461 free(buf);
1462}
1463
1464static int tecmp0 (const void *_a, const void *_b)
1465{
1466 struct tree_entry *a = *((struct tree_entry**)_a);
1467 struct tree_entry *b = *((struct tree_entry**)_b);
1468 return base_name_compare(
1469 a->name->str_dat, a->name->str_len, a->versions[0].mode,
1470 b->name->str_dat, b->name->str_len, b->versions[0].mode);
1471}
1472
1473static int tecmp1 (const void *_a, const void *_b)
1474{
1475 struct tree_entry *a = *((struct tree_entry**)_a);
1476 struct tree_entry *b = *((struct tree_entry**)_b);
1477 return base_name_compare(
1478 a->name->str_dat, a->name->str_len, a->versions[1].mode,
1479 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1480}
1481
1482static void mktree(struct tree_content *t, int v, struct strbuf *b)
1483{
1484 size_t maxlen = 0;
1485 unsigned int i;
1486
1487 if (!v)
1488 QSORT(t->entries, t->entry_count, tecmp0);
1489 else
1490 QSORT(t->entries, t->entry_count, tecmp1);
1491
1492 for (i = 0; i < t->entry_count; i++) {
1493 if (t->entries[i]->versions[v].mode)
1494 maxlen += t->entries[i]->name->str_len + 34;
1495 }
1496
1497 strbuf_reset(b);
1498 strbuf_grow(b, maxlen);
1499 for (i = 0; i < t->entry_count; i++) {
1500 struct tree_entry *e = t->entries[i];
1501 if (!e->versions[v].mode)
1502 continue;
1503 strbuf_addf(b, "%o %s%c",
1504 (unsigned int)(e->versions[v].mode & ~NO_DELTA),
1505 e->name->str_dat, '\0');
1506 strbuf_add(b, e->versions[v].oid.hash, GIT_SHA1_RAWSZ);
1507 }
1508}
1509
1510static void store_tree(struct tree_entry *root)
1511{
1512 struct tree_content *t;
1513 unsigned int i, j, del;
1514 struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1515 struct object_entry *le = NULL;
1516
1517 if (!is_null_oid(&root->versions[1].oid))
1518 return;
1519
1520 if (!root->tree)
1521 load_tree(root);
1522 t = root->tree;
1523
1524 for (i = 0; i < t->entry_count; i++) {
1525 if (t->entries[i]->tree)
1526 store_tree(t->entries[i]);
1527 }
1528
1529 if (!(root->versions[0].mode & NO_DELTA))
1530 le = find_object(&root->versions[0].oid);
1531 if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1532 mktree(t, 0, &old_tree);
1533 lo.data = old_tree;
1534 lo.offset = le->idx.offset;
1535 lo.depth = t->delta_depth;
1536 }
1537
1538 mktree(t, 1, &new_tree);
1539 store_object(OBJ_TREE, &new_tree, &lo, &root->versions[1].oid, 0);
1540
1541 t->delta_depth = lo.depth;
1542 for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1543 struct tree_entry *e = t->entries[i];
1544 if (e->versions[1].mode) {
1545 e->versions[0].mode = e->versions[1].mode;
1546 oidcpy(&e->versions[0].oid, &e->versions[1].oid);
1547 t->entries[j++] = e;
1548 } else {
1549 release_tree_entry(e);
1550 del++;
1551 }
1552 }
1553 t->entry_count -= del;
1554}
1555
1556static void tree_content_replace(
1557 struct tree_entry *root,
1558 const struct object_id *oid,
1559 const uint16_t mode,
1560 struct tree_content *newtree)
1561{
1562 if (!S_ISDIR(mode))
1563 die("Root cannot be a non-directory");
1564 oidclr(&root->versions[0].oid);
1565 oidcpy(&root->versions[1].oid, oid);
1566 if (root->tree)
1567 release_tree_content_recursive(root->tree);
1568 root->tree = newtree;
1569}
1570
1571static int tree_content_set(
1572 struct tree_entry *root,
1573 const char *p,
1574 const struct object_id *oid,
1575 const uint16_t mode,
1576 struct tree_content *subtree)
1577{
1578 struct tree_content *t;
1579 const char *slash1;
1580 unsigned int i, n;
1581 struct tree_entry *e;
1582
1583 slash1 = strchrnul(p, '/');
1584 n = slash1 - p;
1585 if (!n)
1586 die("Empty path component found in input");
1587 if (!*slash1 && !S_ISDIR(mode) && subtree)
1588 die("Non-directories cannot have subtrees");
1589
1590 if (!root->tree)
1591 load_tree(root);
1592 t = root->tree;
1593 for (i = 0; i < t->entry_count; i++) {
1594 e = t->entries[i];
1595 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1596 if (!*slash1) {
1597 if (!S_ISDIR(mode)
1598 && e->versions[1].mode == mode
1599 && !oidcmp(&e->versions[1].oid, oid))
1600 return 0;
1601 e->versions[1].mode = mode;
1602 oidcpy(&e->versions[1].oid, oid);
1603 if (e->tree)
1604 release_tree_content_recursive(e->tree);
1605 e->tree = subtree;
1606
1607 /*
1608 * We need to leave e->versions[0].sha1 alone
1609 * to avoid modifying the preimage tree used
1610 * when writing out the parent directory.
1611 * But after replacing the subdir with a
1612 * completely different one, it's not a good
1613 * delta base any more, and besides, we've
1614 * thrown away the tree entries needed to
1615 * make a delta against it.
1616 *
1617 * So let's just explicitly disable deltas
1618 * for the subtree.
1619 */
1620 if (S_ISDIR(e->versions[0].mode))
1621 e->versions[0].mode |= NO_DELTA;
1622
1623 oidclr(&root->versions[1].oid);
1624 return 1;
1625 }
1626 if (!S_ISDIR(e->versions[1].mode)) {
1627 e->tree = new_tree_content(8);
1628 e->versions[1].mode = S_IFDIR;
1629 }
1630 if (!e->tree)
1631 load_tree(e);
1632 if (tree_content_set(e, slash1 + 1, oid, mode, subtree)) {
1633 oidclr(&root->versions[1].oid);
1634 return 1;
1635 }
1636 return 0;
1637 }
1638 }
1639
1640 if (t->entry_count == t->entry_capacity)
1641 root->tree = t = grow_tree_content(t, t->entry_count);
1642 e = new_tree_entry();
1643 e->name = to_atom(p, n);
1644 e->versions[0].mode = 0;
1645 oidclr(&e->versions[0].oid);
1646 t->entries[t->entry_count++] = e;
1647 if (*slash1) {
1648 e->tree = new_tree_content(8);
1649 e->versions[1].mode = S_IFDIR;
1650 tree_content_set(e, slash1 + 1, oid, mode, subtree);
1651 } else {
1652 e->tree = subtree;
1653 e->versions[1].mode = mode;
1654 oidcpy(&e->versions[1].oid, oid);
1655 }
1656 oidclr(&root->versions[1].oid);
1657 return 1;
1658}
1659
1660static int tree_content_remove(
1661 struct tree_entry *root,
1662 const char *p,
1663 struct tree_entry *backup_leaf,
1664 int allow_root)
1665{
1666 struct tree_content *t;
1667 const char *slash1;
1668 unsigned int i, n;
1669 struct tree_entry *e;
1670
1671 slash1 = strchrnul(p, '/');
1672 n = slash1 - p;
1673
1674 if (!root->tree)
1675 load_tree(root);
1676
1677 if (!*p && allow_root) {
1678 e = root;
1679 goto del_entry;
1680 }
1681
1682 t = root->tree;
1683 for (i = 0; i < t->entry_count; i++) {
1684 e = t->entries[i];
1685 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1686 if (*slash1 && !S_ISDIR(e->versions[1].mode))
1687 /*
1688 * If p names a file in some subdirectory, and a
1689 * file or symlink matching the name of the
1690 * parent directory of p exists, then p cannot
1691 * exist and need not be deleted.
1692 */
1693 return 1;
1694 if (!*slash1 || !S_ISDIR(e->versions[1].mode))
1695 goto del_entry;
1696 if (!e->tree)
1697 load_tree(e);
1698 if (tree_content_remove(e, slash1 + 1, backup_leaf, 0)) {
1699 for (n = 0; n < e->tree->entry_count; n++) {
1700 if (e->tree->entries[n]->versions[1].mode) {
1701 oidclr(&root->versions[1].oid);
1702 return 1;
1703 }
1704 }
1705 backup_leaf = NULL;
1706 goto del_entry;
1707 }
1708 return 0;
1709 }
1710 }
1711 return 0;
1712
1713del_entry:
1714 if (backup_leaf)
1715 memcpy(backup_leaf, e, sizeof(*backup_leaf));
1716 else if (e->tree)
1717 release_tree_content_recursive(e->tree);
1718 e->tree = NULL;
1719 e->versions[1].mode = 0;
1720 oidclr(&e->versions[1].oid);
1721 oidclr(&root->versions[1].oid);
1722 return 1;
1723}
1724
1725static int tree_content_get(
1726 struct tree_entry *root,
1727 const char *p,
1728 struct tree_entry *leaf,
1729 int allow_root)
1730{
1731 struct tree_content *t;
1732 const char *slash1;
1733 unsigned int i, n;
1734 struct tree_entry *e;
1735
1736 slash1 = strchrnul(p, '/');
1737 n = slash1 - p;
1738 if (!n && !allow_root)
1739 die("Empty path component found in input");
1740
1741 if (!root->tree)
1742 load_tree(root);
1743
1744 if (!n) {
1745 e = root;
1746 goto found_entry;
1747 }
1748
1749 t = root->tree;
1750 for (i = 0; i < t->entry_count; i++) {
1751 e = t->entries[i];
1752 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1753 if (!*slash1)
1754 goto found_entry;
1755 if (!S_ISDIR(e->versions[1].mode))
1756 return 0;
1757 if (!e->tree)
1758 load_tree(e);
1759 return tree_content_get(e, slash1 + 1, leaf, 0);
1760 }
1761 }
1762 return 0;
1763
1764found_entry:
1765 memcpy(leaf, e, sizeof(*leaf));
1766 if (e->tree && is_null_oid(&e->versions[1].oid))
1767 leaf->tree = dup_tree_content(e->tree);
1768 else
1769 leaf->tree = NULL;
1770 return 1;
1771}
1772
1773static int update_branch(struct branch *b)
1774{
1775 static const char *msg = "fast-import";
1776 struct ref_transaction *transaction;
1777 struct object_id old_oid;
1778 struct strbuf err = STRBUF_INIT;
1779
1780 if (is_null_oid(&b->oid)) {
1781 if (b->delete)
1782 delete_ref(NULL, b->name, NULL, 0);
1783 return 0;
1784 }
1785 if (read_ref(b->name, &old_oid))
1786 oidclr(&old_oid);
1787 if (!force_update && !is_null_oid(&old_oid)) {
1788 struct commit *old_cmit, *new_cmit;
1789
1790 old_cmit = lookup_commit_reference_gently(&old_oid, 0);
1791 new_cmit = lookup_commit_reference_gently(&b->oid, 0);
1792 if (!old_cmit || !new_cmit)
1793 return error("Branch %s is missing commits.", b->name);
1794
1795 if (!in_merge_bases(old_cmit, new_cmit)) {
1796 warning("Not updating %s"
1797 " (new tip %s does not contain %s)",
1798 b->name, oid_to_hex(&b->oid),
1799 oid_to_hex(&old_oid));
1800 return -1;
1801 }
1802 }
1803 transaction = ref_transaction_begin(&err);
1804 if (!transaction ||
1805 ref_transaction_update(transaction, b->name, &b->oid, &old_oid,
1806 0, msg, &err) ||
1807 ref_transaction_commit(transaction, &err)) {
1808 ref_transaction_free(transaction);
1809 error("%s", err.buf);
1810 strbuf_release(&err);
1811 return -1;
1812 }
1813 ref_transaction_free(transaction);
1814 strbuf_release(&err);
1815 return 0;
1816}
1817
1818static void dump_branches(void)
1819{
1820 unsigned int i;
1821 struct branch *b;
1822
1823 for (i = 0; i < branch_table_sz; i++) {
1824 for (b = branch_table[i]; b; b = b->table_next_branch)
1825 failure |= update_branch(b);
1826 }
1827}
1828
1829static void dump_tags(void)
1830{
1831 static const char *msg = "fast-import";
1832 struct tag *t;
1833 struct strbuf ref_name = STRBUF_INIT;
1834 struct strbuf err = STRBUF_INIT;
1835 struct ref_transaction *transaction;
1836
1837 transaction = ref_transaction_begin(&err);
1838 if (!transaction) {
1839 failure |= error("%s", err.buf);
1840 goto cleanup;
1841 }
1842 for (t = first_tag; t; t = t->next_tag) {
1843 strbuf_reset(&ref_name);
1844 strbuf_addf(&ref_name, "refs/tags/%s", t->name);
1845
1846 if (ref_transaction_update(transaction, ref_name.buf,
1847 &t->oid, NULL, 0, msg, &err)) {
1848 failure |= error("%s", err.buf);
1849 goto cleanup;
1850 }
1851 }
1852 if (ref_transaction_commit(transaction, &err))
1853 failure |= error("%s", err.buf);
1854
1855 cleanup:
1856 ref_transaction_free(transaction);
1857 strbuf_release(&ref_name);
1858 strbuf_release(&err);
1859}
1860
1861static void dump_marks_helper(FILE *f,
1862 uintmax_t base,
1863 struct mark_set *m)
1864{
1865 uintmax_t k;
1866 if (m->shift) {
1867 for (k = 0; k < 1024; k++) {
1868 if (m->data.sets[k])
1869 dump_marks_helper(f, base + (k << m->shift),
1870 m->data.sets[k]);
1871 }
1872 } else {
1873 for (k = 0; k < 1024; k++) {
1874 if (m->data.marked[k])
1875 fprintf(f, ":%" PRIuMAX " %s\n", base + k,
1876 oid_to_hex(&m->data.marked[k]->idx.oid));
1877 }
1878 }
1879}
1880
1881static void dump_marks(void)
1882{
1883 static struct lock_file mark_lock;
1884 FILE *f;
1885
1886 if (!export_marks_file || (import_marks_file && !import_marks_file_done))
1887 return;
1888
1889 if (hold_lock_file_for_update(&mark_lock, export_marks_file, 0) < 0) {
1890 failure |= error_errno("Unable to write marks file %s",
1891 export_marks_file);
1892 return;
1893 }
1894
1895 f = fdopen_lock_file(&mark_lock, "w");
1896 if (!f) {
1897 int saved_errno = errno;
1898 rollback_lock_file(&mark_lock);
1899 failure |= error("Unable to write marks file %s: %s",
1900 export_marks_file, strerror(saved_errno));
1901 return;
1902 }
1903
1904 dump_marks_helper(f, 0, marks);
1905 if (commit_lock_file(&mark_lock)) {
1906 failure |= error_errno("Unable to write file %s",
1907 export_marks_file);
1908 return;
1909 }
1910}
1911
1912static void read_marks(void)
1913{
1914 char line[512];
1915 FILE *f = fopen(import_marks_file, "r");
1916 if (f)
1917 ;
1918 else if (import_marks_file_ignore_missing && errno == ENOENT)
1919 goto done; /* Marks file does not exist */
1920 else
1921 die_errno("cannot read '%s'", import_marks_file);
1922 while (fgets(line, sizeof(line), f)) {
1923 uintmax_t mark;
1924 char *end;
1925 struct object_id oid;
1926 struct object_entry *e;
1927
1928 end = strchr(line, '\n');
1929 if (line[0] != ':' || !end)
1930 die("corrupt mark line: %s", line);
1931 *end = 0;
1932 mark = strtoumax(line + 1, &end, 10);
1933 if (!mark || end == line + 1
1934 || *end != ' ' || get_oid_hex(end + 1, &oid))
1935 die("corrupt mark line: %s", line);
1936 e = find_object(&oid);
1937 if (!e) {
1938 enum object_type type = sha1_object_info(oid.hash, NULL);
1939 if (type < 0)
1940 die("object not found: %s", oid_to_hex(&oid));
1941 e = insert_object(&oid);
1942 e->type = type;
1943 e->pack_id = MAX_PACK_ID;
1944 e->idx.offset = 1; /* just not zero! */
1945 }
1946 insert_mark(mark, e);
1947 }
1948 fclose(f);
1949done:
1950 import_marks_file_done = 1;
1951}
1952
1953
1954static int read_next_command(void)
1955{
1956 static int stdin_eof = 0;
1957
1958 if (stdin_eof) {
1959 unread_command_buf = 0;
1960 return EOF;
1961 }
1962
1963 for (;;) {
1964 const char *p;
1965
1966 if (unread_command_buf) {
1967 unread_command_buf = 0;
1968 } else {
1969 struct recent_command *rc;
1970
1971 strbuf_detach(&command_buf, NULL);
1972 stdin_eof = strbuf_getline_lf(&command_buf, stdin);
1973 if (stdin_eof)
1974 return EOF;
1975
1976 if (!seen_data_command
1977 && !starts_with(command_buf.buf, "feature ")
1978 && !starts_with(command_buf.buf, "option ")) {
1979 parse_argv();
1980 }
1981
1982 rc = rc_free;
1983 if (rc)
1984 rc_free = rc->next;
1985 else {
1986 rc = cmd_hist.next;
1987 cmd_hist.next = rc->next;
1988 cmd_hist.next->prev = &cmd_hist;
1989 free(rc->buf);
1990 }
1991
1992 rc->buf = command_buf.buf;
1993 rc->prev = cmd_tail;
1994 rc->next = cmd_hist.prev;
1995 rc->prev->next = rc;
1996 cmd_tail = rc;
1997 }
1998 if (skip_prefix(command_buf.buf, "get-mark ", &p)) {
1999 parse_get_mark(p);
2000 continue;
2001 }
2002 if (skip_prefix(command_buf.buf, "cat-blob ", &p)) {
2003 parse_cat_blob(p);
2004 continue;
2005 }
2006 if (command_buf.buf[0] == '#')
2007 continue;
2008 return 0;
2009 }
2010}
2011
2012static void skip_optional_lf(void)
2013{
2014 int term_char = fgetc(stdin);
2015 if (term_char != '\n' && term_char != EOF)
2016 ungetc(term_char, stdin);
2017}
2018
2019static void parse_mark(void)
2020{
2021 const char *v;
2022 if (skip_prefix(command_buf.buf, "mark :", &v)) {
2023 next_mark = strtoumax(v, NULL, 10);
2024 read_next_command();
2025 }
2026 else
2027 next_mark = 0;
2028}
2029
2030static int parse_data(struct strbuf *sb, uintmax_t limit, uintmax_t *len_res)
2031{
2032 const char *data;
2033 strbuf_reset(sb);
2034
2035 if (!skip_prefix(command_buf.buf, "data ", &data))
2036 die("Expected 'data n' command, found: %s", command_buf.buf);
2037
2038 if (skip_prefix(data, "<<", &data)) {
2039 char *term = xstrdup(data);
2040 size_t term_len = command_buf.len - (data - command_buf.buf);
2041
2042 strbuf_detach(&command_buf, NULL);
2043 for (;;) {
2044 if (strbuf_getline_lf(&command_buf, stdin) == EOF)
2045 die("EOF in data (terminator '%s' not found)", term);
2046 if (term_len == command_buf.len
2047 && !strcmp(term, command_buf.buf))
2048 break;
2049 strbuf_addbuf(sb, &command_buf);
2050 strbuf_addch(sb, '\n');
2051 }
2052 free(term);
2053 }
2054 else {
2055 uintmax_t len = strtoumax(data, NULL, 10);
2056 size_t n = 0, length = (size_t)len;
2057
2058 if (limit && limit < len) {
2059 *len_res = len;
2060 return 0;
2061 }
2062 if (length < len)
2063 die("data is too large to use in this context");
2064
2065 while (n < length) {
2066 size_t s = strbuf_fread(sb, length - n, stdin);
2067 if (!s && feof(stdin))
2068 die("EOF in data (%lu bytes remaining)",
2069 (unsigned long)(length - n));
2070 n += s;
2071 }
2072 }
2073
2074 skip_optional_lf();
2075 return 1;
2076}
2077
2078static int validate_raw_date(const char *src, struct strbuf *result)
2079{
2080 const char *orig_src = src;
2081 char *endp;
2082 unsigned long num;
2083
2084 errno = 0;
2085
2086 num = strtoul(src, &endp, 10);
2087 /* NEEDSWORK: perhaps check for reasonable values? */
2088 if (errno || endp == src || *endp != ' ')
2089 return -1;
2090
2091 src = endp + 1;
2092 if (*src != '-' && *src != '+')
2093 return -1;
2094
2095 num = strtoul(src + 1, &endp, 10);
2096 if (errno || endp == src + 1 || *endp || 1400 < num)
2097 return -1;
2098
2099 strbuf_addstr(result, orig_src);
2100 return 0;
2101}
2102
2103static char *parse_ident(const char *buf)
2104{
2105 const char *ltgt;
2106 size_t name_len;
2107 struct strbuf ident = STRBUF_INIT;
2108
2109 /* ensure there is a space delimiter even if there is no name */
2110 if (*buf == '<')
2111 --buf;
2112
2113 ltgt = buf + strcspn(buf, "<>");
2114 if (*ltgt != '<')
2115 die("Missing < in ident string: %s", buf);
2116 if (ltgt != buf && ltgt[-1] != ' ')
2117 die("Missing space before < in ident string: %s", buf);
2118 ltgt = ltgt + 1 + strcspn(ltgt + 1, "<>");
2119 if (*ltgt != '>')
2120 die("Missing > in ident string: %s", buf);
2121 ltgt++;
2122 if (*ltgt != ' ')
2123 die("Missing space after > in ident string: %s", buf);
2124 ltgt++;
2125 name_len = ltgt - buf;
2126 strbuf_add(&ident, buf, name_len);
2127
2128 switch (whenspec) {
2129 case WHENSPEC_RAW:
2130 if (validate_raw_date(ltgt, &ident) < 0)
2131 die("Invalid raw date \"%s\" in ident: %s", ltgt, buf);
2132 break;
2133 case WHENSPEC_RFC2822:
2134 if (parse_date(ltgt, &ident) < 0)
2135 die("Invalid rfc2822 date \"%s\" in ident: %s", ltgt, buf);
2136 break;
2137 case WHENSPEC_NOW:
2138 if (strcmp("now", ltgt))
2139 die("Date in ident must be 'now': %s", buf);
2140 datestamp(&ident);
2141 break;
2142 }
2143
2144 return strbuf_detach(&ident, NULL);
2145}
2146
2147static void parse_and_store_blob(
2148 struct last_object *last,
2149 struct object_id *oidout,
2150 uintmax_t mark)
2151{
2152 static struct strbuf buf = STRBUF_INIT;
2153 uintmax_t len;
2154
2155 if (parse_data(&buf, big_file_threshold, &len))
2156 store_object(OBJ_BLOB, &buf, last, oidout, mark);
2157 else {
2158 if (last) {
2159 strbuf_release(&last->data);
2160 last->offset = 0;
2161 last->depth = 0;
2162 }
2163 stream_blob(len, oidout, mark);
2164 skip_optional_lf();
2165 }
2166}
2167
2168static void parse_new_blob(void)
2169{
2170 read_next_command();
2171 parse_mark();
2172 parse_and_store_blob(&last_blob, NULL, next_mark);
2173}
2174
2175static void unload_one_branch(void)
2176{
2177 while (cur_active_branches
2178 && cur_active_branches >= max_active_branches) {
2179 uintmax_t min_commit = ULONG_MAX;
2180 struct branch *e, *l = NULL, *p = NULL;
2181
2182 for (e = active_branches; e; e = e->active_next_branch) {
2183 if (e->last_commit < min_commit) {
2184 p = l;
2185 min_commit = e->last_commit;
2186 }
2187 l = e;
2188 }
2189
2190 if (p) {
2191 e = p->active_next_branch;
2192 p->active_next_branch = e->active_next_branch;
2193 } else {
2194 e = active_branches;
2195 active_branches = e->active_next_branch;
2196 }
2197 e->active = 0;
2198 e->active_next_branch = NULL;
2199 if (e->branch_tree.tree) {
2200 release_tree_content_recursive(e->branch_tree.tree);
2201 e->branch_tree.tree = NULL;
2202 }
2203 cur_active_branches--;
2204 }
2205}
2206
2207static void load_branch(struct branch *b)
2208{
2209 load_tree(&b->branch_tree);
2210 if (!b->active) {
2211 b->active = 1;
2212 b->active_next_branch = active_branches;
2213 active_branches = b;
2214 cur_active_branches++;
2215 branch_load_count++;
2216 }
2217}
2218
2219static unsigned char convert_num_notes_to_fanout(uintmax_t num_notes)
2220{
2221 unsigned char fanout = 0;
2222 while ((num_notes >>= 8))
2223 fanout++;
2224 return fanout;
2225}
2226
2227static void construct_path_with_fanout(const char *hex_sha1,
2228 unsigned char fanout, char *path)
2229{
2230 unsigned int i = 0, j = 0;
2231 if (fanout >= the_hash_algo->rawsz)
2232 die("Too large fanout (%u)", fanout);
2233 while (fanout) {
2234 path[i++] = hex_sha1[j++];
2235 path[i++] = hex_sha1[j++];
2236 path[i++] = '/';
2237 fanout--;
2238 }
2239 memcpy(path + i, hex_sha1 + j, the_hash_algo->hexsz - j);
2240 path[i + the_hash_algo->hexsz - j] = '\0';
2241}
2242
2243static uintmax_t do_change_note_fanout(
2244 struct tree_entry *orig_root, struct tree_entry *root,
2245 char *hex_oid, unsigned int hex_oid_len,
2246 char *fullpath, unsigned int fullpath_len,
2247 unsigned char fanout)
2248{
2249 struct tree_content *t;
2250 struct tree_entry *e, leaf;
2251 unsigned int i, tmp_hex_oid_len, tmp_fullpath_len;
2252 uintmax_t num_notes = 0;
2253 struct object_id oid;
2254 char realpath[60];
2255
2256 if (!root->tree)
2257 load_tree(root);
2258 t = root->tree;
2259
2260 for (i = 0; t && i < t->entry_count; i++) {
2261 e = t->entries[i];
2262 tmp_hex_oid_len = hex_oid_len + e->name->str_len;
2263 tmp_fullpath_len = fullpath_len;
2264
2265 /*
2266 * We're interested in EITHER existing note entries (entries
2267 * with exactly 40 hex chars in path, not including directory
2268 * separators), OR directory entries that may contain note
2269 * entries (with < 40 hex chars in path).
2270 * Also, each path component in a note entry must be a multiple
2271 * of 2 chars.
2272 */
2273 if (!e->versions[1].mode ||
2274 tmp_hex_oid_len > GIT_SHA1_HEXSZ ||
2275 e->name->str_len % 2)
2276 continue;
2277
2278 /* This _may_ be a note entry, or a subdir containing notes */
2279 memcpy(hex_oid + hex_oid_len, e->name->str_dat,
2280 e->name->str_len);
2281 if (tmp_fullpath_len)
2282 fullpath[tmp_fullpath_len++] = '/';
2283 memcpy(fullpath + tmp_fullpath_len, e->name->str_dat,
2284 e->name->str_len);
2285 tmp_fullpath_len += e->name->str_len;
2286 fullpath[tmp_fullpath_len] = '\0';
2287
2288 if (tmp_hex_oid_len == GIT_SHA1_HEXSZ && !get_oid_hex(hex_oid, &oid)) {
2289 /* This is a note entry */
2290 if (fanout == 0xff) {
2291 /* Counting mode, no rename */
2292 num_notes++;
2293 continue;
2294 }
2295 construct_path_with_fanout(hex_oid, fanout, realpath);
2296 if (!strcmp(fullpath, realpath)) {
2297 /* Note entry is in correct location */
2298 num_notes++;
2299 continue;
2300 }
2301
2302 /* Rename fullpath to realpath */
2303 if (!tree_content_remove(orig_root, fullpath, &leaf, 0))
2304 die("Failed to remove path %s", fullpath);
2305 tree_content_set(orig_root, realpath,
2306 &leaf.versions[1].oid,
2307 leaf.versions[1].mode,
2308 leaf.tree);
2309 } else if (S_ISDIR(e->versions[1].mode)) {
2310 /* This is a subdir that may contain note entries */
2311 num_notes += do_change_note_fanout(orig_root, e,
2312 hex_oid, tmp_hex_oid_len,
2313 fullpath, tmp_fullpath_len, fanout);
2314 }
2315
2316 /* The above may have reallocated the current tree_content */
2317 t = root->tree;
2318 }
2319 return num_notes;
2320}
2321
2322static uintmax_t change_note_fanout(struct tree_entry *root,
2323 unsigned char fanout)
2324{
2325 /*
2326 * The size of path is due to one slash between every two hex digits,
2327 * plus the terminating NUL. Note that there is no slash at the end, so
2328 * the number of slashes is one less than half the number of hex
2329 * characters.
2330 */
2331 char hex_oid[GIT_MAX_HEXSZ], path[GIT_MAX_HEXSZ + (GIT_MAX_HEXSZ / 2) - 1 + 1];
2332 return do_change_note_fanout(root, root, hex_oid, 0, path, 0, fanout);
2333}
2334
2335/*
2336 * Given a pointer into a string, parse a mark reference:
2337 *
2338 * idnum ::= ':' bigint;
2339 *
2340 * Return the first character after the value in *endptr.
2341 *
2342 * Complain if the following character is not what is expected,
2343 * either a space or end of the string.
2344 */
2345static uintmax_t parse_mark_ref(const char *p, char **endptr)
2346{
2347 uintmax_t mark;
2348
2349 assert(*p == ':');
2350 p++;
2351 mark = strtoumax(p, endptr, 10);
2352 if (*endptr == p)
2353 die("No value after ':' in mark: %s", command_buf.buf);
2354 return mark;
2355}
2356
2357/*
2358 * Parse the mark reference, and complain if this is not the end of
2359 * the string.
2360 */
2361static uintmax_t parse_mark_ref_eol(const char *p)
2362{
2363 char *end;
2364 uintmax_t mark;
2365
2366 mark = parse_mark_ref(p, &end);
2367 if (*end != '\0')
2368 die("Garbage after mark: %s", command_buf.buf);
2369 return mark;
2370}
2371
2372/*
2373 * Parse the mark reference, demanding a trailing space. Return a
2374 * pointer to the space.
2375 */
2376static uintmax_t parse_mark_ref_space(const char **p)
2377{
2378 uintmax_t mark;
2379 char *end;
2380
2381 mark = parse_mark_ref(*p, &end);
2382 if (*end++ != ' ')
2383 die("Missing space after mark: %s", command_buf.buf);
2384 *p = end;
2385 return mark;
2386}
2387
2388static void file_change_m(const char *p, struct branch *b)
2389{
2390 static struct strbuf uq = STRBUF_INIT;
2391 const char *endp;
2392 struct object_entry *oe;
2393 struct object_id oid;
2394 uint16_t mode, inline_data = 0;
2395
2396 p = get_mode(p, &mode);
2397 if (!p)
2398 die("Corrupt mode: %s", command_buf.buf);
2399 switch (mode) {
2400 case 0644:
2401 case 0755:
2402 mode |= S_IFREG;
2403 case S_IFREG | 0644:
2404 case S_IFREG | 0755:
2405 case S_IFLNK:
2406 case S_IFDIR:
2407 case S_IFGITLINK:
2408 /* ok */
2409 break;
2410 default:
2411 die("Corrupt mode: %s", command_buf.buf);
2412 }
2413
2414 if (*p == ':') {
2415 oe = find_mark(parse_mark_ref_space(&p));
2416 oidcpy(&oid, &oe->idx.oid);
2417 } else if (skip_prefix(p, "inline ", &p)) {
2418 inline_data = 1;
2419 oe = NULL; /* not used with inline_data, but makes gcc happy */
2420 } else {
2421 if (parse_oid_hex(p, &oid, &p))
2422 die("Invalid dataref: %s", command_buf.buf);
2423 oe = find_object(&oid);
2424 if (*p++ != ' ')
2425 die("Missing space after SHA1: %s", command_buf.buf);
2426 }
2427
2428 strbuf_reset(&uq);
2429 if (!unquote_c_style(&uq, p, &endp)) {
2430 if (*endp)
2431 die("Garbage after path in: %s", command_buf.buf);
2432 p = uq.buf;
2433 }
2434
2435 /* Git does not track empty, non-toplevel directories. */
2436 if (S_ISDIR(mode) && is_empty_tree_oid(&oid) && *p) {
2437 tree_content_remove(&b->branch_tree, p, NULL, 0);
2438 return;
2439 }
2440
2441 if (S_ISGITLINK(mode)) {
2442 if (inline_data)
2443 die("Git links cannot be specified 'inline': %s",
2444 command_buf.buf);
2445 else if (oe) {
2446 if (oe->type != OBJ_COMMIT)
2447 die("Not a commit (actually a %s): %s",
2448 type_name(oe->type), command_buf.buf);
2449 }
2450 /*
2451 * Accept the sha1 without checking; it expected to be in
2452 * another repository.
2453 */
2454 } else if (inline_data) {
2455 if (S_ISDIR(mode))
2456 die("Directories cannot be specified 'inline': %s",
2457 command_buf.buf);
2458 if (p != uq.buf) {
2459 strbuf_addstr(&uq, p);
2460 p = uq.buf;
2461 }
2462 read_next_command();
2463 parse_and_store_blob(&last_blob, &oid, 0);
2464 } else {
2465 enum object_type expected = S_ISDIR(mode) ?
2466 OBJ_TREE: OBJ_BLOB;
2467 enum object_type type = oe ? oe->type :
2468 sha1_object_info(oid.hash, NULL);
2469 if (type < 0)
2470 die("%s not found: %s",
2471 S_ISDIR(mode) ? "Tree" : "Blob",
2472 command_buf.buf);
2473 if (type != expected)
2474 die("Not a %s (actually a %s): %s",
2475 type_name(expected), type_name(type),
2476 command_buf.buf);
2477 }
2478
2479 if (!*p) {
2480 tree_content_replace(&b->branch_tree, &oid, mode, NULL);
2481 return;
2482 }
2483 tree_content_set(&b->branch_tree, p, &oid, mode, NULL);
2484}
2485
2486static void file_change_d(const char *p, struct branch *b)
2487{
2488 static struct strbuf uq = STRBUF_INIT;
2489 const char *endp;
2490
2491 strbuf_reset(&uq);
2492 if (!unquote_c_style(&uq, p, &endp)) {
2493 if (*endp)
2494 die("Garbage after path in: %s", command_buf.buf);
2495 p = uq.buf;
2496 }
2497 tree_content_remove(&b->branch_tree, p, NULL, 1);
2498}
2499
2500static void file_change_cr(const char *s, struct branch *b, int rename)
2501{
2502 const char *d;
2503 static struct strbuf s_uq = STRBUF_INIT;
2504 static struct strbuf d_uq = STRBUF_INIT;
2505 const char *endp;
2506 struct tree_entry leaf;
2507
2508 strbuf_reset(&s_uq);
2509 if (!unquote_c_style(&s_uq, s, &endp)) {
2510 if (*endp != ' ')
2511 die("Missing space after source: %s", command_buf.buf);
2512 } else {
2513 endp = strchr(s, ' ');
2514 if (!endp)
2515 die("Missing space after source: %s", command_buf.buf);
2516 strbuf_add(&s_uq, s, endp - s);
2517 }
2518 s = s_uq.buf;
2519
2520 endp++;
2521 if (!*endp)
2522 die("Missing dest: %s", command_buf.buf);
2523
2524 d = endp;
2525 strbuf_reset(&d_uq);
2526 if (!unquote_c_style(&d_uq, d, &endp)) {
2527 if (*endp)
2528 die("Garbage after dest in: %s", command_buf.buf);
2529 d = d_uq.buf;
2530 }
2531
2532 memset(&leaf, 0, sizeof(leaf));
2533 if (rename)
2534 tree_content_remove(&b->branch_tree, s, &leaf, 1);
2535 else
2536 tree_content_get(&b->branch_tree, s, &leaf, 1);
2537 if (!leaf.versions[1].mode)
2538 die("Path %s not in branch", s);
2539 if (!*d) { /* C "path/to/subdir" "" */
2540 tree_content_replace(&b->branch_tree,
2541 &leaf.versions[1].oid,
2542 leaf.versions[1].mode,
2543 leaf.tree);
2544 return;
2545 }
2546 tree_content_set(&b->branch_tree, d,
2547 &leaf.versions[1].oid,
2548 leaf.versions[1].mode,
2549 leaf.tree);
2550}
2551
2552static void note_change_n(const char *p, struct branch *b, unsigned char *old_fanout)
2553{
2554 static struct strbuf uq = STRBUF_INIT;
2555 struct object_entry *oe;
2556 struct branch *s;
2557 struct object_id oid, commit_oid;
2558 char path[60];
2559 uint16_t inline_data = 0;
2560 unsigned char new_fanout;
2561
2562 /*
2563 * When loading a branch, we don't traverse its tree to count the real
2564 * number of notes (too expensive to do this for all non-note refs).
2565 * This means that recently loaded notes refs might incorrectly have
2566 * b->num_notes == 0, and consequently, old_fanout might be wrong.
2567 *
2568 * Fix this by traversing the tree and counting the number of notes
2569 * when b->num_notes == 0. If the notes tree is truly empty, the
2570 * calculation should not take long.
2571 */
2572 if (b->num_notes == 0 && *old_fanout == 0) {
2573 /* Invoke change_note_fanout() in "counting mode". */
2574 b->num_notes = change_note_fanout(&b->branch_tree, 0xff);
2575 *old_fanout = convert_num_notes_to_fanout(b->num_notes);
2576 }
2577
2578 /* Now parse the notemodify command. */
2579 /* <dataref> or 'inline' */
2580 if (*p == ':') {
2581 oe = find_mark(parse_mark_ref_space(&p));
2582 oidcpy(&oid, &oe->idx.oid);
2583 } else if (skip_prefix(p, "inline ", &p)) {
2584 inline_data = 1;
2585 oe = NULL; /* not used with inline_data, but makes gcc happy */
2586 } else {
2587 if (parse_oid_hex(p, &oid, &p))
2588 die("Invalid dataref: %s", command_buf.buf);
2589 oe = find_object(&oid);
2590 if (*p++ != ' ')
2591 die("Missing space after SHA1: %s", command_buf.buf);
2592 }
2593
2594 /* <commit-ish> */
2595 s = lookup_branch(p);
2596 if (s) {
2597 if (is_null_oid(&s->oid))
2598 die("Can't add a note on empty branch.");
2599 oidcpy(&commit_oid, &s->oid);
2600 } else if (*p == ':') {
2601 uintmax_t commit_mark = parse_mark_ref_eol(p);
2602 struct object_entry *commit_oe = find_mark(commit_mark);
2603 if (commit_oe->type != OBJ_COMMIT)
2604 die("Mark :%" PRIuMAX " not a commit", commit_mark);
2605 oidcpy(&commit_oid, &commit_oe->idx.oid);
2606 } else if (!get_oid(p, &commit_oid)) {
2607 unsigned long size;
2608 char *buf = read_object_with_reference(commit_oid.hash,
2609 commit_type, &size, commit_oid.hash);
2610 if (!buf || size < 46)
2611 die("Not a valid commit: %s", p);
2612 free(buf);
2613 } else
2614 die("Invalid ref name or SHA1 expression: %s", p);
2615
2616 if (inline_data) {
2617 if (p != uq.buf) {
2618 strbuf_addstr(&uq, p);
2619 p = uq.buf;
2620 }
2621 read_next_command();
2622 parse_and_store_blob(&last_blob, &oid, 0);
2623 } else if (oe) {
2624 if (oe->type != OBJ_BLOB)
2625 die("Not a blob (actually a %s): %s",
2626 type_name(oe->type), command_buf.buf);
2627 } else if (!is_null_oid(&oid)) {
2628 enum object_type type = sha1_object_info(oid.hash, NULL);
2629 if (type < 0)
2630 die("Blob not found: %s", command_buf.buf);
2631 if (type != OBJ_BLOB)
2632 die("Not a blob (actually a %s): %s",
2633 type_name(type), command_buf.buf);
2634 }
2635
2636 construct_path_with_fanout(oid_to_hex(&commit_oid), *old_fanout, path);
2637 if (tree_content_remove(&b->branch_tree, path, NULL, 0))
2638 b->num_notes--;
2639
2640 if (is_null_oid(&oid))
2641 return; /* nothing to insert */
2642
2643 b->num_notes++;
2644 new_fanout = convert_num_notes_to_fanout(b->num_notes);
2645 construct_path_with_fanout(oid_to_hex(&commit_oid), new_fanout, path);
2646 tree_content_set(&b->branch_tree, path, &oid, S_IFREG | 0644, NULL);
2647}
2648
2649static void file_change_deleteall(struct branch *b)
2650{
2651 release_tree_content_recursive(b->branch_tree.tree);
2652 oidclr(&b->branch_tree.versions[0].oid);
2653 oidclr(&b->branch_tree.versions[1].oid);
2654 load_tree(&b->branch_tree);
2655 b->num_notes = 0;
2656}
2657
2658static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2659{
2660 if (!buf || size < GIT_SHA1_HEXSZ + 6)
2661 die("Not a valid commit: %s", oid_to_hex(&b->oid));
2662 if (memcmp("tree ", buf, 5)
2663 || get_oid_hex(buf + 5, &b->branch_tree.versions[1].oid))
2664 die("The commit %s is corrupt", oid_to_hex(&b->oid));
2665 oidcpy(&b->branch_tree.versions[0].oid,
2666 &b->branch_tree.versions[1].oid);
2667}
2668
2669static void parse_from_existing(struct branch *b)
2670{
2671 if (is_null_oid(&b->oid)) {
2672 oidclr(&b->branch_tree.versions[0].oid);
2673 oidclr(&b->branch_tree.versions[1].oid);
2674 } else {
2675 unsigned long size;
2676 char *buf;
2677
2678 buf = read_object_with_reference(b->oid.hash,
2679 commit_type, &size,
2680 b->oid.hash);
2681 parse_from_commit(b, buf, size);
2682 free(buf);
2683 }
2684}
2685
2686static int parse_from(struct branch *b)
2687{
2688 const char *from;
2689 struct branch *s;
2690 struct object_id oid;
2691
2692 if (!skip_prefix(command_buf.buf, "from ", &from))
2693 return 0;
2694
2695 oidcpy(&oid, &b->branch_tree.versions[1].oid);
2696
2697 s = lookup_branch(from);
2698 if (b == s)
2699 die("Can't create a branch from itself: %s", b->name);
2700 else if (s) {
2701 struct object_id *t = &s->branch_tree.versions[1].oid;
2702 oidcpy(&b->oid, &s->oid);
2703 oidcpy(&b->branch_tree.versions[0].oid, t);
2704 oidcpy(&b->branch_tree.versions[1].oid, t);
2705 } else if (*from == ':') {
2706 uintmax_t idnum = parse_mark_ref_eol(from);
2707 struct object_entry *oe = find_mark(idnum);
2708 if (oe->type != OBJ_COMMIT)
2709 die("Mark :%" PRIuMAX " not a commit", idnum);
2710 if (oidcmp(&b->oid, &oe->idx.oid)) {
2711 oidcpy(&b->oid, &oe->idx.oid);
2712 if (oe->pack_id != MAX_PACK_ID) {
2713 unsigned long size;
2714 char *buf = gfi_unpack_entry(oe, &size);
2715 parse_from_commit(b, buf, size);
2716 free(buf);
2717 } else
2718 parse_from_existing(b);
2719 }
2720 } else if (!get_oid(from, &b->oid)) {
2721 parse_from_existing(b);
2722 if (is_null_oid(&b->oid))
2723 b->delete = 1;
2724 }
2725 else
2726 die("Invalid ref name or SHA1 expression: %s", from);
2727
2728 if (b->branch_tree.tree && oidcmp(&oid, &b->branch_tree.versions[1].oid)) {
2729 release_tree_content_recursive(b->branch_tree.tree);
2730 b->branch_tree.tree = NULL;
2731 }
2732
2733 read_next_command();
2734 return 1;
2735}
2736
2737static struct hash_list *parse_merge(unsigned int *count)
2738{
2739 struct hash_list *list = NULL, **tail = &list, *n;
2740 const char *from;
2741 struct branch *s;
2742
2743 *count = 0;
2744 while (skip_prefix(command_buf.buf, "merge ", &from)) {
2745 n = xmalloc(sizeof(*n));
2746 s = lookup_branch(from);
2747 if (s)
2748 oidcpy(&n->oid, &s->oid);
2749 else if (*from == ':') {
2750 uintmax_t idnum = parse_mark_ref_eol(from);
2751 struct object_entry *oe = find_mark(idnum);
2752 if (oe->type != OBJ_COMMIT)
2753 die("Mark :%" PRIuMAX " not a commit", idnum);
2754 oidcpy(&n->oid, &oe->idx.oid);
2755 } else if (!get_oid(from, &n->oid)) {
2756 unsigned long size;
2757 char *buf = read_object_with_reference(n->oid.hash,
2758 commit_type, &size, n->oid.hash);
2759 if (!buf || size < 46)
2760 die("Not a valid commit: %s", from);
2761 free(buf);
2762 } else
2763 die("Invalid ref name or SHA1 expression: %s", from);
2764
2765 n->next = NULL;
2766 *tail = n;
2767 tail = &n->next;
2768
2769 (*count)++;
2770 read_next_command();
2771 }
2772 return list;
2773}
2774
2775static void parse_new_commit(const char *arg)
2776{
2777 static struct strbuf msg = STRBUF_INIT;
2778 struct branch *b;
2779 char *author = NULL;
2780 char *committer = NULL;
2781 struct hash_list *merge_list = NULL;
2782 unsigned int merge_count;
2783 unsigned char prev_fanout, new_fanout;
2784 const char *v;
2785
2786 b = lookup_branch(arg);
2787 if (!b)
2788 b = new_branch(arg);
2789
2790 read_next_command();
2791 parse_mark();
2792 if (skip_prefix(command_buf.buf, "author ", &v)) {
2793 author = parse_ident(v);
2794 read_next_command();
2795 }
2796 if (skip_prefix(command_buf.buf, "committer ", &v)) {
2797 committer = parse_ident(v);
2798 read_next_command();
2799 }
2800 if (!committer)
2801 die("Expected committer but didn't get one");
2802 parse_data(&msg, 0, NULL);
2803 read_next_command();
2804 parse_from(b);
2805 merge_list = parse_merge(&merge_count);
2806
2807 /* ensure the branch is active/loaded */
2808 if (!b->branch_tree.tree || !max_active_branches) {
2809 unload_one_branch();
2810 load_branch(b);
2811 }
2812
2813 prev_fanout = convert_num_notes_to_fanout(b->num_notes);
2814
2815 /* file_change* */
2816 while (command_buf.len > 0) {
2817 if (skip_prefix(command_buf.buf, "M ", &v))
2818 file_change_m(v, b);
2819 else if (skip_prefix(command_buf.buf, "D ", &v))
2820 file_change_d(v, b);
2821 else if (skip_prefix(command_buf.buf, "R ", &v))
2822 file_change_cr(v, b, 1);
2823 else if (skip_prefix(command_buf.buf, "C ", &v))
2824 file_change_cr(v, b, 0);
2825 else if (skip_prefix(command_buf.buf, "N ", &v))
2826 note_change_n(v, b, &prev_fanout);
2827 else if (!strcmp("deleteall", command_buf.buf))
2828 file_change_deleteall(b);
2829 else if (skip_prefix(command_buf.buf, "ls ", &v))
2830 parse_ls(v, b);
2831 else {
2832 unread_command_buf = 1;
2833 break;
2834 }
2835 if (read_next_command() == EOF)
2836 break;
2837 }
2838
2839 new_fanout = convert_num_notes_to_fanout(b->num_notes);
2840 if (new_fanout != prev_fanout)
2841 b->num_notes = change_note_fanout(&b->branch_tree, new_fanout);
2842
2843 /* build the tree and the commit */
2844 store_tree(&b->branch_tree);
2845 oidcpy(&b->branch_tree.versions[0].oid,
2846 &b->branch_tree.versions[1].oid);
2847
2848 strbuf_reset(&new_data);
2849 strbuf_addf(&new_data, "tree %s\n",
2850 oid_to_hex(&b->branch_tree.versions[1].oid));
2851 if (!is_null_oid(&b->oid))
2852 strbuf_addf(&new_data, "parent %s\n",
2853 oid_to_hex(&b->oid));
2854 while (merge_list) {
2855 struct hash_list *next = merge_list->next;
2856 strbuf_addf(&new_data, "parent %s\n",
2857 oid_to_hex(&merge_list->oid));
2858 free(merge_list);
2859 merge_list = next;
2860 }
2861 strbuf_addf(&new_data,
2862 "author %s\n"
2863 "committer %s\n"
2864 "\n",
2865 author ? author : committer, committer);
2866 strbuf_addbuf(&new_data, &msg);
2867 free(author);
2868 free(committer);
2869
2870 if (!store_object(OBJ_COMMIT, &new_data, NULL, &b->oid, next_mark))
2871 b->pack_id = pack_id;
2872 b->last_commit = object_count_by_type[OBJ_COMMIT];
2873}
2874
2875static void parse_new_tag(const char *arg)
2876{
2877 static struct strbuf msg = STRBUF_INIT;
2878 const char *from;
2879 char *tagger;
2880 struct branch *s;
2881 struct tag *t;
2882 uintmax_t from_mark = 0;
2883 struct object_id oid;
2884 enum object_type type;
2885 const char *v;
2886
2887 t = mem_pool_alloc(&fi_mem_pool, sizeof(struct tag));
2888 memset(t, 0, sizeof(struct tag));
2889 t->name = pool_strdup(arg);
2890 if (last_tag)
2891 last_tag->next_tag = t;
2892 else
2893 first_tag = t;
2894 last_tag = t;
2895 read_next_command();
2896
2897 /* from ... */
2898 if (!skip_prefix(command_buf.buf, "from ", &from))
2899 die("Expected from command, got %s", command_buf.buf);
2900 s = lookup_branch(from);
2901 if (s) {
2902 if (is_null_oid(&s->oid))
2903 die("Can't tag an empty branch.");
2904 oidcpy(&oid, &s->oid);
2905 type = OBJ_COMMIT;
2906 } else if (*from == ':') {
2907 struct object_entry *oe;
2908 from_mark = parse_mark_ref_eol(from);
2909 oe = find_mark(from_mark);
2910 type = oe->type;
2911 oidcpy(&oid, &oe->idx.oid);
2912 } else if (!get_oid(from, &oid)) {
2913 struct object_entry *oe = find_object(&oid);
2914 if (!oe) {
2915 type = sha1_object_info(oid.hash, NULL);
2916 if (type < 0)
2917 die("Not a valid object: %s", from);
2918 } else
2919 type = oe->type;
2920 } else
2921 die("Invalid ref name or SHA1 expression: %s", from);
2922 read_next_command();
2923
2924 /* tagger ... */
2925 if (skip_prefix(command_buf.buf, "tagger ", &v)) {
2926 tagger = parse_ident(v);
2927 read_next_command();
2928 } else
2929 tagger = NULL;
2930
2931 /* tag payload/message */
2932 parse_data(&msg, 0, NULL);
2933
2934 /* build the tag object */
2935 strbuf_reset(&new_data);
2936
2937 strbuf_addf(&new_data,
2938 "object %s\n"
2939 "type %s\n"
2940 "tag %s\n",
2941 oid_to_hex(&oid), type_name(type), t->name);
2942 if (tagger)
2943 strbuf_addf(&new_data,
2944 "tagger %s\n", tagger);
2945 strbuf_addch(&new_data, '\n');
2946 strbuf_addbuf(&new_data, &msg);
2947 free(tagger);
2948
2949 if (store_object(OBJ_TAG, &new_data, NULL, &t->oid, 0))
2950 t->pack_id = MAX_PACK_ID;
2951 else
2952 t->pack_id = pack_id;
2953}
2954
2955static void parse_reset_branch(const char *arg)
2956{
2957 struct branch *b;
2958
2959 b = lookup_branch(arg);
2960 if (b) {
2961 oidclr(&b->oid);
2962 oidclr(&b->branch_tree.versions[0].oid);
2963 oidclr(&b->branch_tree.versions[1].oid);
2964 if (b->branch_tree.tree) {
2965 release_tree_content_recursive(b->branch_tree.tree);
2966 b->branch_tree.tree = NULL;
2967 }
2968 }
2969 else
2970 b = new_branch(arg);
2971 read_next_command();
2972 parse_from(b);
2973 if (command_buf.len > 0)
2974 unread_command_buf = 1;
2975}
2976
2977static void cat_blob_write(const char *buf, unsigned long size)
2978{
2979 if (write_in_full(cat_blob_fd, buf, size) < 0)
2980 die_errno("Write to frontend failed");
2981}
2982
2983static void cat_blob(struct object_entry *oe, struct object_id *oid)
2984{
2985 struct strbuf line = STRBUF_INIT;
2986 unsigned long size;
2987 enum object_type type = 0;
2988 char *buf;
2989
2990 if (!oe || oe->pack_id == MAX_PACK_ID) {
2991 buf = read_sha1_file(oid->hash, &type, &size);
2992 } else {
2993 type = oe->type;
2994 buf = gfi_unpack_entry(oe, &size);
2995 }
2996
2997 /*
2998 * Output based on batch_one_object() from cat-file.c.
2999 */
3000 if (type <= 0) {
3001 strbuf_reset(&line);
3002 strbuf_addf(&line, "%s missing\n", oid_to_hex(oid));
3003 cat_blob_write(line.buf, line.len);
3004 strbuf_release(&line);
3005 free(buf);
3006 return;
3007 }
3008 if (!buf)
3009 die("Can't read object %s", oid_to_hex(oid));
3010 if (type != OBJ_BLOB)
3011 die("Object %s is a %s but a blob was expected.",
3012 oid_to_hex(oid), type_name(type));
3013 strbuf_reset(&line);
3014 strbuf_addf(&line, "%s %s %lu\n", oid_to_hex(oid),
3015 type_name(type), size);
3016 cat_blob_write(line.buf, line.len);
3017 strbuf_release(&line);
3018 cat_blob_write(buf, size);
3019 cat_blob_write("\n", 1);
3020 if (oe && oe->pack_id == pack_id) {
3021 last_blob.offset = oe->idx.offset;
3022 strbuf_attach(&last_blob.data, buf, size, size);
3023 last_blob.depth = oe->depth;
3024 } else
3025 free(buf);
3026}
3027
3028static void parse_get_mark(const char *p)
3029{
3030 struct object_entry *oe;
3031 char output[GIT_MAX_HEXSZ + 2];
3032
3033 /* get-mark SP <object> LF */
3034 if (*p != ':')
3035 die("Not a mark: %s", p);
3036
3037 oe = find_mark(parse_mark_ref_eol(p));
3038 if (!oe)
3039 die("Unknown mark: %s", command_buf.buf);
3040
3041 xsnprintf(output, sizeof(output), "%s\n", oid_to_hex(&oe->idx.oid));
3042 cat_blob_write(output, GIT_SHA1_HEXSZ + 1);
3043}
3044
3045static void parse_cat_blob(const char *p)
3046{
3047 struct object_entry *oe;
3048 struct object_id oid;
3049
3050 /* cat-blob SP <object> LF */
3051 if (*p == ':') {
3052 oe = find_mark(parse_mark_ref_eol(p));
3053 if (!oe)
3054 die("Unknown mark: %s", command_buf.buf);
3055 oidcpy(&oid, &oe->idx.oid);
3056 } else {
3057 if (parse_oid_hex(p, &oid, &p))
3058 die("Invalid dataref: %s", command_buf.buf);
3059 if (*p)
3060 die("Garbage after SHA1: %s", command_buf.buf);
3061 oe = find_object(&oid);
3062 }
3063
3064 cat_blob(oe, &oid);
3065}
3066
3067static struct object_entry *dereference(struct object_entry *oe,
3068 struct object_id *oid)
3069{
3070 unsigned long size;
3071 char *buf = NULL;
3072 if (!oe) {
3073 enum object_type type = sha1_object_info(oid->hash, NULL);
3074 if (type < 0)
3075 die("object not found: %s", oid_to_hex(oid));
3076 /* cache it! */
3077 oe = insert_object(oid);
3078 oe->type = type;
3079 oe->pack_id = MAX_PACK_ID;
3080 oe->idx.offset = 1;
3081 }
3082 switch (oe->type) {
3083 case OBJ_TREE: /* easy case. */
3084 return oe;
3085 case OBJ_COMMIT:
3086 case OBJ_TAG:
3087 break;
3088 default:
3089 die("Not a tree-ish: %s", command_buf.buf);
3090 }
3091
3092 if (oe->pack_id != MAX_PACK_ID) { /* in a pack being written */
3093 buf = gfi_unpack_entry(oe, &size);
3094 } else {
3095 enum object_type unused;
3096 buf = read_sha1_file(oid->hash, &unused, &size);
3097 }
3098 if (!buf)
3099 die("Can't load object %s", oid_to_hex(oid));
3100
3101 /* Peel one layer. */
3102 switch (oe->type) {
3103 case OBJ_TAG:
3104 if (size < GIT_SHA1_HEXSZ + strlen("object ") ||
3105 get_oid_hex(buf + strlen("object "), oid))
3106 die("Invalid SHA1 in tag: %s", command_buf.buf);
3107 break;
3108 case OBJ_COMMIT:
3109 if (size < GIT_SHA1_HEXSZ + strlen("tree ") ||
3110 get_oid_hex(buf + strlen("tree "), oid))
3111 die("Invalid SHA1 in commit: %s", command_buf.buf);
3112 }
3113
3114 free(buf);
3115 return find_object(oid);
3116}
3117
3118static struct object_entry *parse_treeish_dataref(const char **p)
3119{
3120 struct object_id oid;
3121 struct object_entry *e;
3122
3123 if (**p == ':') { /* <mark> */
3124 e = find_mark(parse_mark_ref_space(p));
3125 if (!e)
3126 die("Unknown mark: %s", command_buf.buf);
3127 oidcpy(&oid, &e->idx.oid);
3128 } else { /* <sha1> */
3129 if (parse_oid_hex(*p, &oid, p))
3130 die("Invalid dataref: %s", command_buf.buf);
3131 e = find_object(&oid);
3132 if (*(*p)++ != ' ')
3133 die("Missing space after tree-ish: %s", command_buf.buf);
3134 }
3135
3136 while (!e || e->type != OBJ_TREE)
3137 e = dereference(e, &oid);
3138 return e;
3139}
3140
3141static void print_ls(int mode, const unsigned char *sha1, const char *path)
3142{
3143 static struct strbuf line = STRBUF_INIT;
3144
3145 /* See show_tree(). */
3146 const char *type =
3147 S_ISGITLINK(mode) ? commit_type :
3148 S_ISDIR(mode) ? tree_type :
3149 blob_type;
3150
3151 if (!mode) {
3152 /* missing SP path LF */
3153 strbuf_reset(&line);
3154 strbuf_addstr(&line, "missing ");
3155 quote_c_style(path, &line, NULL, 0);
3156 strbuf_addch(&line, '\n');
3157 } else {
3158 /* mode SP type SP object_name TAB path LF */
3159 strbuf_reset(&line);
3160 strbuf_addf(&line, "%06o %s %s\t",
3161 mode & ~NO_DELTA, type, sha1_to_hex(sha1));
3162 quote_c_style(path, &line, NULL, 0);
3163 strbuf_addch(&line, '\n');
3164 }
3165 cat_blob_write(line.buf, line.len);
3166}
3167
3168static void parse_ls(const char *p, struct branch *b)
3169{
3170 struct tree_entry *root = NULL;
3171 struct tree_entry leaf = {NULL};
3172
3173 /* ls SP (<tree-ish> SP)? <path> */
3174 if (*p == '"') {
3175 if (!b)
3176 die("Not in a commit: %s", command_buf.buf);
3177 root = &b->branch_tree;
3178 } else {
3179 struct object_entry *e = parse_treeish_dataref(&p);
3180 root = new_tree_entry();
3181 oidcpy(&root->versions[1].oid, &e->idx.oid);
3182 if (!is_null_oid(&root->versions[1].oid))
3183 root->versions[1].mode = S_IFDIR;
3184 load_tree(root);
3185 }
3186 if (*p == '"') {
3187 static struct strbuf uq = STRBUF_INIT;
3188 const char *endp;
3189 strbuf_reset(&uq);
3190 if (unquote_c_style(&uq, p, &endp))
3191 die("Invalid path: %s", command_buf.buf);
3192 if (*endp)
3193 die("Garbage after path in: %s", command_buf.buf);
3194 p = uq.buf;
3195 }
3196 tree_content_get(root, p, &leaf, 1);
3197 /*
3198 * A directory in preparation would have a sha1 of zero
3199 * until it is saved. Save, for simplicity.
3200 */
3201 if (S_ISDIR(leaf.versions[1].mode))
3202 store_tree(&leaf);
3203
3204 print_ls(leaf.versions[1].mode, leaf.versions[1].oid.hash, p);
3205 if (leaf.tree)
3206 release_tree_content_recursive(leaf.tree);
3207 if (!b || root != &b->branch_tree)
3208 release_tree_entry(root);
3209}
3210
3211static void checkpoint(void)
3212{
3213 checkpoint_requested = 0;
3214 if (object_count) {
3215 cycle_packfile();
3216 }
3217 dump_branches();
3218 dump_tags();
3219 dump_marks();
3220}
3221
3222static void parse_checkpoint(void)
3223{
3224 checkpoint_requested = 1;
3225 skip_optional_lf();
3226}
3227
3228static void parse_progress(void)
3229{
3230 fwrite(command_buf.buf, 1, command_buf.len, stdout);
3231 fputc('\n', stdout);
3232 fflush(stdout);
3233 skip_optional_lf();
3234}
3235
3236static char* make_fast_import_path(const char *path)
3237{
3238 if (!relative_marks_paths || is_absolute_path(path))
3239 return xstrdup(path);
3240 return git_pathdup("info/fast-import/%s", path);
3241}
3242
3243static void option_import_marks(const char *marks,
3244 int from_stream, int ignore_missing)
3245{
3246 if (import_marks_file) {
3247 if (from_stream)
3248 die("Only one import-marks command allowed per stream");
3249
3250 /* read previous mark file */
3251 if(!import_marks_file_from_stream)
3252 read_marks();
3253 }
3254
3255 import_marks_file = make_fast_import_path(marks);
3256 safe_create_leading_directories_const(import_marks_file);
3257 import_marks_file_from_stream = from_stream;
3258 import_marks_file_ignore_missing = ignore_missing;
3259}
3260
3261static void option_date_format(const char *fmt)
3262{
3263 if (!strcmp(fmt, "raw"))
3264 whenspec = WHENSPEC_RAW;
3265 else if (!strcmp(fmt, "rfc2822"))
3266 whenspec = WHENSPEC_RFC2822;
3267 else if (!strcmp(fmt, "now"))
3268 whenspec = WHENSPEC_NOW;
3269 else
3270 die("unknown --date-format argument %s", fmt);
3271}
3272
3273static unsigned long ulong_arg(const char *option, const char *arg)
3274{
3275 char *endptr;
3276 unsigned long rv = strtoul(arg, &endptr, 0);
3277 if (strchr(arg, '-') || endptr == arg || *endptr)
3278 die("%s: argument must be a non-negative integer", option);
3279 return rv;
3280}
3281
3282static void option_depth(const char *depth)
3283{
3284 max_depth = ulong_arg("--depth", depth);
3285 if (max_depth > MAX_DEPTH)
3286 die("--depth cannot exceed %u", MAX_DEPTH);
3287}
3288
3289static void option_active_branches(const char *branches)
3290{
3291 max_active_branches = ulong_arg("--active-branches", branches);
3292}
3293
3294static void option_export_marks(const char *marks)
3295{
3296 export_marks_file = make_fast_import_path(marks);
3297 safe_create_leading_directories_const(export_marks_file);
3298}
3299
3300static void option_cat_blob_fd(const char *fd)
3301{
3302 unsigned long n = ulong_arg("--cat-blob-fd", fd);
3303 if (n > (unsigned long) INT_MAX)
3304 die("--cat-blob-fd cannot exceed %d", INT_MAX);
3305 cat_blob_fd = (int) n;
3306}
3307
3308static void option_export_pack_edges(const char *edges)
3309{
3310 if (pack_edges)
3311 fclose(pack_edges);
3312 pack_edges = xfopen(edges, "a");
3313}
3314
3315static int parse_one_option(const char *option)
3316{
3317 if (skip_prefix(option, "max-pack-size=", &option)) {
3318 unsigned long v;
3319 if (!git_parse_ulong(option, &v))
3320 return 0;
3321 if (v < 8192) {
3322 warning("max-pack-size is now in bytes, assuming --max-pack-size=%lum", v);
3323 v *= 1024 * 1024;
3324 } else if (v < 1024 * 1024) {
3325 warning("minimum max-pack-size is 1 MiB");
3326 v = 1024 * 1024;
3327 }
3328 max_packsize = v;
3329 } else if (skip_prefix(option, "big-file-threshold=", &option)) {
3330 unsigned long v;
3331 if (!git_parse_ulong(option, &v))
3332 return 0;
3333 big_file_threshold = v;
3334 } else if (skip_prefix(option, "depth=", &option)) {
3335 option_depth(option);
3336 } else if (skip_prefix(option, "active-branches=", &option)) {
3337 option_active_branches(option);
3338 } else if (skip_prefix(option, "export-pack-edges=", &option)) {
3339 option_export_pack_edges(option);
3340 } else if (starts_with(option, "quiet")) {
3341 show_stats = 0;
3342 } else if (starts_with(option, "stats")) {
3343 show_stats = 1;
3344 } else {
3345 return 0;
3346 }
3347
3348 return 1;
3349}
3350
3351static int parse_one_feature(const char *feature, int from_stream)
3352{
3353 const char *arg;
3354
3355 if (skip_prefix(feature, "date-format=", &arg)) {
3356 option_date_format(arg);
3357 } else if (skip_prefix(feature, "import-marks=", &arg)) {
3358 option_import_marks(arg, from_stream, 0);
3359 } else if (skip_prefix(feature, "import-marks-if-exists=", &arg)) {
3360 option_import_marks(arg, from_stream, 1);
3361 } else if (skip_prefix(feature, "export-marks=", &arg)) {
3362 option_export_marks(arg);
3363 } else if (!strcmp(feature, "get-mark")) {
3364 ; /* Don't die - this feature is supported */
3365 } else if (!strcmp(feature, "cat-blob")) {
3366 ; /* Don't die - this feature is supported */
3367 } else if (!strcmp(feature, "relative-marks")) {
3368 relative_marks_paths = 1;
3369 } else if (!strcmp(feature, "no-relative-marks")) {
3370 relative_marks_paths = 0;
3371 } else if (!strcmp(feature, "done")) {
3372 require_explicit_termination = 1;
3373 } else if (!strcmp(feature, "force")) {
3374 force_update = 1;
3375 } else if (!strcmp(feature, "notes") || !strcmp(feature, "ls")) {
3376 ; /* do nothing; we have the feature */
3377 } else {
3378 return 0;
3379 }
3380
3381 return 1;
3382}
3383
3384static void parse_feature(const char *feature)
3385{
3386 if (seen_data_command)
3387 die("Got feature command '%s' after data command", feature);
3388
3389 if (parse_one_feature(feature, 1))
3390 return;
3391
3392 die("This version of fast-import does not support feature %s.", feature);
3393}
3394
3395static void parse_option(const char *option)
3396{
3397 if (seen_data_command)
3398 die("Got option command '%s' after data command", option);
3399
3400 if (parse_one_option(option))
3401 return;
3402
3403 die("This version of fast-import does not support option: %s", option);
3404}
3405
3406static void git_pack_config(void)
3407{
3408 int indexversion_value;
3409 int limit;
3410 unsigned long packsizelimit_value;
3411
3412 if (!git_config_get_ulong("pack.depth", &max_depth)) {
3413 if (max_depth > MAX_DEPTH)
3414 max_depth = MAX_DEPTH;
3415 }
3416 if (!git_config_get_int("pack.indexversion", &indexversion_value)) {
3417 pack_idx_opts.version = indexversion_value;
3418 if (pack_idx_opts.version > 2)
3419 git_die_config("pack.indexversion",
3420 "bad pack.indexversion=%"PRIu32, pack_idx_opts.version);
3421 }
3422 if (!git_config_get_ulong("pack.packsizelimit", &packsizelimit_value))
3423 max_packsize = packsizelimit_value;
3424
3425 if (!git_config_get_int("fastimport.unpacklimit", &limit))
3426 unpack_limit = limit;
3427 else if (!git_config_get_int("transfer.unpacklimit", &limit))
3428 unpack_limit = limit;
3429
3430 git_config(git_default_config, NULL);
3431}
3432
3433static const char fast_import_usage[] =
3434"git fast-import [--date-format=<f>] [--max-pack-size=<n>] [--big-file-threshold=<n>] [--depth=<n>] [--active-branches=<n>] [--export-marks=<marks.file>]";
3435
3436static void parse_argv(void)
3437{
3438 unsigned int i;
3439
3440 for (i = 1; i < global_argc; i++) {
3441 const char *a = global_argv[i];
3442
3443 if (*a != '-' || !strcmp(a, "--"))
3444 break;
3445
3446 if (!skip_prefix(a, "--", &a))
3447 die("unknown option %s", a);
3448
3449 if (parse_one_option(a))
3450 continue;
3451
3452 if (parse_one_feature(a, 0))
3453 continue;
3454
3455 if (skip_prefix(a, "cat-blob-fd=", &a)) {
3456 option_cat_blob_fd(a);
3457 continue;
3458 }
3459
3460 die("unknown option --%s", a);
3461 }
3462 if (i != global_argc)
3463 usage(fast_import_usage);
3464
3465 seen_data_command = 1;
3466 if (import_marks_file)
3467 read_marks();
3468}
3469
3470int cmd_main(int argc, const char **argv)
3471{
3472 unsigned int i;
3473
3474 if (argc == 2 && !strcmp(argv[1], "-h"))
3475 usage(fast_import_usage);
3476
3477 setup_git_directory();
3478 reset_pack_idx_option(&pack_idx_opts);
3479 git_pack_config();
3480
3481 alloc_objects(object_entry_alloc);
3482 strbuf_init(&command_buf, 0);
3483 atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
3484 branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
3485 avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
3486 marks = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
3487
3488 global_argc = argc;
3489 global_argv = argv;
3490
3491 rc_free = mem_pool_alloc(&fi_mem_pool, cmd_save * sizeof(*rc_free));
3492 for (i = 0; i < (cmd_save - 1); i++)
3493 rc_free[i].next = &rc_free[i + 1];
3494 rc_free[cmd_save - 1].next = NULL;
3495
3496 prepare_packed_git();
3497 start_packfile();
3498 set_die_routine(die_nicely);
3499 set_checkpoint_signal();
3500 while (read_next_command() != EOF) {
3501 const char *v;
3502 if (!strcmp("blob", command_buf.buf))
3503 parse_new_blob();
3504 else if (skip_prefix(command_buf.buf, "ls ", &v))
3505 parse_ls(v, NULL);
3506 else if (skip_prefix(command_buf.buf, "commit ", &v))
3507 parse_new_commit(v);
3508 else if (skip_prefix(command_buf.buf, "tag ", &v))
3509 parse_new_tag(v);
3510 else if (skip_prefix(command_buf.buf, "reset ", &v))
3511 parse_reset_branch(v);
3512 else if (!strcmp("checkpoint", command_buf.buf))
3513 parse_checkpoint();
3514 else if (!strcmp("done", command_buf.buf))
3515 break;
3516 else if (starts_with(command_buf.buf, "progress "))
3517 parse_progress();
3518 else if (skip_prefix(command_buf.buf, "feature ", &v))
3519 parse_feature(v);
3520 else if (skip_prefix(command_buf.buf, "option git ", &v))
3521 parse_option(v);
3522 else if (starts_with(command_buf.buf, "option "))
3523 /* ignore non-git options*/;
3524 else
3525 die("Unsupported command: %s", command_buf.buf);
3526
3527 if (checkpoint_requested)
3528 checkpoint();
3529 }
3530
3531 /* argv hasn't been parsed yet, do so */
3532 if (!seen_data_command)
3533 parse_argv();
3534
3535 if (require_explicit_termination && feof(stdin))
3536 die("stream ends early");
3537
3538 end_packfile();
3539
3540 dump_branches();
3541 dump_tags();
3542 unkeep_all_packs();
3543 dump_marks();
3544
3545 if (pack_edges)
3546 fclose(pack_edges);
3547
3548 if (show_stats) {
3549 uintmax_t total_count = 0, duplicate_count = 0;
3550 for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
3551 total_count += object_count_by_type[i];
3552 for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
3553 duplicate_count += duplicate_count_by_type[i];
3554
3555 fprintf(stderr, "%s statistics:\n", argv[0]);
3556 fprintf(stderr, "---------------------------------------------------------------------\n");
3557 fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
3558 fprintf(stderr, "Total objects: %10" PRIuMAX " (%10" PRIuMAX " duplicates )\n", total_count, duplicate_count);
3559 fprintf(stderr, " blobs : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB], delta_count_attempts_by_type[OBJ_BLOB]);
3560 fprintf(stderr, " trees : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE], delta_count_attempts_by_type[OBJ_TREE]);
3561 fprintf(stderr, " commits: %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT], delta_count_attempts_by_type[OBJ_COMMIT]);
3562 fprintf(stderr, " tags : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG], delta_count_attempts_by_type[OBJ_TAG]);
3563 fprintf(stderr, "Total branches: %10lu (%10lu loads )\n", branch_count, branch_load_count);
3564 fprintf(stderr, " marks: %10" PRIuMAX " (%10" PRIuMAX " unique )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
3565 fprintf(stderr, " atoms: %10u\n", atom_cnt);
3566 fprintf(stderr, "Memory total: %10" PRIuMAX " KiB\n", (total_allocd + fi_mem_pool.pool_alloc + alloc_count*sizeof(struct object_entry))/1024);
3567 fprintf(stderr, " pools: %10lu KiB\n", (unsigned long)((total_allocd + fi_mem_pool.pool_alloc) /1024));
3568 fprintf(stderr, " objects: %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
3569 fprintf(stderr, "---------------------------------------------------------------------\n");
3570 pack_report();
3571 fprintf(stderr, "---------------------------------------------------------------------\n");
3572 fprintf(stderr, "\n");
3573 }
3574
3575 return failure ? 1 : 0;
3576}