remote-hg: get the correct refs
[git/dscho.git] / fast-import.c
blobdcfb8fa909c3207de61a6fbb206cd2d8e3d8f1f7
1 /*
2 (See Documentation/git-fast-import.txt for maintained documentation.)
3 Format of STDIN stream:
5 stream ::= cmd*;
7 cmd ::= new_blob
8 | new_commit
9 | new_tag
10 | reset_branch
11 | checkpoint
12 | progress
15 new_blob ::= 'blob' lf
16 mark?
17 file_content;
18 file_content ::= data;
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 (ref_str | hexsha1 | sha1exp_str | idnum) lf)?
26 ('merge' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf)*
27 file_change*
28 lf?;
29 commit_msg ::= data;
31 file_change ::= file_clr
32 | file_del
33 | file_rnm
34 | file_cpy
35 | file_obm
36 | file_inm;
37 file_clr ::= 'deleteall' lf;
38 file_del ::= 'D' sp path_str lf;
39 file_rnm ::= 'R' sp path_str sp path_str lf;
40 file_cpy ::= 'C' sp path_str sp path_str lf;
41 file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf;
42 file_inm ::= 'M' sp mode sp 'inline' sp path_str lf
43 data;
45 new_tag ::= 'tag' sp tag_str lf
46 'from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf
47 ('tagger' sp name sp '<' email '>' sp when lf)?
48 tag_msg;
49 tag_msg ::= data;
51 reset_branch ::= 'reset' sp ref_str lf
52 ('from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf)?
53 lf?;
55 checkpoint ::= 'checkpoint' lf
56 lf?;
58 progress ::= 'progress' sp not_lf* lf
59 lf?;
61 # note: the first idnum in a stream should be 1 and subsequent
62 # idnums should not have gaps between values as this will cause
63 # the stream parser to reserve space for the gapped values. An
64 # idnum can be updated in the future to a new object by issuing
65 # a new mark directive with the old idnum.
67 mark ::= 'mark' sp idnum lf;
68 data ::= (delimited_data | exact_data)
69 lf?;
71 # note: delim may be any string but must not contain lf.
72 # data_line may contain any data but must not be exactly
73 # delim.
74 delimited_data ::= 'data' sp '<<' delim lf
75 (data_line lf)*
76 delim lf;
78 # note: declen indicates the length of binary_data in bytes.
79 # declen does not include the lf preceding the binary data.
81 exact_data ::= 'data' sp declen lf
82 binary_data;
84 # note: quoted strings are C-style quoting supporting \c for
85 # common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn
86 # is the signed byte value in octal. Note that the only
87 # characters which must actually be escaped to protect the
88 # stream formatting is: \, " and LF. Otherwise these values
89 # are UTF8.
91 ref_str ::= ref;
92 sha1exp_str ::= sha1exp;
93 tag_str ::= tag;
94 path_str ::= path | '"' quoted(path) '"' ;
95 mode ::= '100644' | '644'
96 | '100755' | '755'
97 | '120000'
100 declen ::= # unsigned 32 bit value, ascii base10 notation;
101 bigint ::= # unsigned integer value, ascii base10 notation;
102 binary_data ::= # file content, not interpreted;
104 when ::= raw_when | rfc2822_when;
105 raw_when ::= ts sp tz;
106 rfc2822_when ::= # Valid RFC 2822 date and time;
108 sp ::= # ASCII space character;
109 lf ::= # ASCII newline (LF) character;
111 # note: a colon (':') must precede the numerical value assigned to
112 # an idnum. This is to distinguish it from a ref or tag name as
113 # GIT does not permit ':' in ref or tag strings.
115 idnum ::= ':' bigint;
116 path ::= # GIT style file path, e.g. "a/b/c";
117 ref ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT";
118 tag ::= # GIT tag name, e.g. "FIREFOX_1_5";
119 sha1exp ::= # Any valid GIT SHA1 expression;
120 hexsha1 ::= # SHA1 in hexadecimal format;
122 # note: name and email are UTF8 strings, however name must not
123 # contain '<' or lf and email must not contain any of the
124 # following: '<', '>', lf.
126 name ::= # valid GIT author/committer name;
127 email ::= # valid GIT author/committer email;
128 ts ::= # time since the epoch in seconds, ascii base10 notation;
129 tz ::= # GIT style timezone;
131 # note: comments may appear anywhere in the input, except
132 # within a data command. Any form of the data command
133 # always escapes the related input from comment processing.
135 # In case it is not clear, the '#' that starts the comment
136 # must be the first character on that line (an lf
137 # preceded it).
139 comment ::= '#' not_lf* lf;
140 not_lf ::= # Any byte that is not ASCII newline (LF);
143 #include "builtin.h"
144 #include "cache.h"
145 #include "object.h"
146 #include "blob.h"
147 #include "tree.h"
148 #include "commit.h"
149 #include "delta.h"
150 #include "pack.h"
151 #include "refs.h"
152 #include "csum-file.h"
153 #include "quote.h"
154 #include "exec_cmd.h"
156 #define PACK_ID_BITS 16
157 #define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
158 #define DEPTH_BITS 13
159 #define MAX_DEPTH ((1<<DEPTH_BITS)-1)
161 struct object_entry
163 struct object_entry *next;
164 uint32_t offset;
165 uint32_t type : TYPE_BITS,
166 pack_id : PACK_ID_BITS,
167 depth : DEPTH_BITS;
168 unsigned char sha1[20];
171 struct object_entry_pool
173 struct object_entry_pool *next_pool;
174 struct object_entry *next_free;
175 struct object_entry *end;
176 struct object_entry entries[FLEX_ARRAY]; /* more */
179 struct mark_set
181 union {
182 struct object_entry *marked[1024];
183 struct mark_set *sets[1024];
184 } data;
185 unsigned int shift;
188 struct last_object
190 struct strbuf data;
191 uint32_t offset;
192 unsigned int depth;
193 unsigned no_swap : 1;
196 struct mem_pool
198 struct mem_pool *next_pool;
199 char *next_free;
200 char *end;
201 uintmax_t space[FLEX_ARRAY]; /* more */
204 struct atom_str
206 struct atom_str *next_atom;
207 unsigned short str_len;
208 char str_dat[FLEX_ARRAY]; /* more */
211 struct tree_content;
212 struct tree_entry
214 struct tree_content *tree;
215 struct atom_str *name;
216 struct tree_entry_ms
218 uint16_t mode;
219 unsigned char sha1[20];
220 } versions[2];
223 struct tree_content
225 unsigned int entry_capacity; /* must match avail_tree_content */
226 unsigned int entry_count;
227 unsigned int delta_depth;
228 struct tree_entry *entries[FLEX_ARRAY]; /* more */
231 struct avail_tree_content
233 unsigned int entry_capacity; /* must match tree_content */
234 struct avail_tree_content *next_avail;
237 struct branch
239 struct branch *table_next_branch;
240 struct branch *active_next_branch;
241 const char *name;
242 struct tree_entry branch_tree;
243 uintmax_t last_commit;
244 unsigned active : 1;
245 unsigned pack_id : PACK_ID_BITS;
246 unsigned char sha1[20];
249 struct tag
251 struct tag *next_tag;
252 const char *name;
253 unsigned int pack_id;
254 unsigned char sha1[20];
257 struct hash_list
259 struct hash_list *next;
260 unsigned char sha1[20];
263 typedef enum {
264 WHENSPEC_RAW = 1,
265 WHENSPEC_RFC2822,
266 WHENSPEC_NOW,
267 } whenspec_type;
269 struct recent_command
271 struct recent_command *prev;
272 struct recent_command *next;
273 char *buf;
276 /* Configured limits on output */
277 static unsigned long max_depth = 10;
278 static off_t max_packsize = (1LL << 32) - 1;
279 static int force_update;
280 static int pack_compression_level = Z_DEFAULT_COMPRESSION;
281 static int pack_compression_seen;
283 /* Stats and misc. counters */
284 static uintmax_t alloc_count;
285 static uintmax_t marks_set_count;
286 static uintmax_t object_count_by_type[1 << TYPE_BITS];
287 static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
288 static uintmax_t delta_count_by_type[1 << TYPE_BITS];
289 static unsigned long object_count;
290 static unsigned long branch_count;
291 static unsigned long branch_load_count;
292 static int failure;
293 static FILE *pack_edges;
294 static unsigned int show_stats = 1;
295 static int global_argc;
296 static const char **global_argv;
298 /* Memory pools */
299 static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
300 static size_t total_allocd;
301 static struct mem_pool *mem_pool;
303 /* Atom management */
304 static unsigned int atom_table_sz = 4451;
305 static unsigned int atom_cnt;
306 static struct atom_str **atom_table;
308 /* The .pack file being generated */
309 static unsigned int pack_id;
310 static struct packed_git *pack_data;
311 static struct packed_git **all_packs;
312 static unsigned long pack_size;
314 /* Table of objects we've written. */
315 static unsigned int object_entry_alloc = 5000;
316 static struct object_entry_pool *blocks;
317 static struct object_entry *object_table[1 << 16];
318 static struct mark_set *marks;
319 static const char *mark_file;
320 static const char *input_file;
322 /* Our last blob */
323 static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
325 /* Tree management */
326 static unsigned int tree_entry_alloc = 1000;
327 static void *avail_tree_entry;
328 static unsigned int avail_tree_table_sz = 100;
329 static struct avail_tree_content **avail_tree_table;
330 static struct strbuf old_tree = STRBUF_INIT;
331 static struct strbuf new_tree = STRBUF_INIT;
333 /* Branch data */
334 static unsigned long max_active_branches = 5;
335 static unsigned long cur_active_branches;
336 static unsigned long branch_table_sz = 1039;
337 static struct branch **branch_table;
338 static struct branch *active_branches;
340 /* Tag data */
341 static struct tag *first_tag;
342 static struct tag *last_tag;
344 /* Input stream parsing */
345 static whenspec_type whenspec = WHENSPEC_RAW;
346 static struct strbuf command_buf = STRBUF_INIT;
347 static int unread_command_buf;
348 static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
349 static struct recent_command *cmd_tail = &cmd_hist;
350 static struct recent_command *rc_free;
351 static unsigned int cmd_save = 100;
352 static uintmax_t next_mark;
353 static struct strbuf new_data = STRBUF_INIT;
354 static int options_enabled;
355 static int seen_non_option_command;
357 static void parse_argv(void);
359 static void write_branch_report(FILE *rpt, struct branch *b)
361 fprintf(rpt, "%s:\n", b->name);
363 fprintf(rpt, " status :");
364 if (b->active)
365 fputs(" active", rpt);
366 if (b->branch_tree.tree)
367 fputs(" loaded", rpt);
368 if (is_null_sha1(b->branch_tree.versions[1].sha1))
369 fputs(" dirty", rpt);
370 fputc('\n', rpt);
372 fprintf(rpt, " tip commit : %s\n", sha1_to_hex(b->sha1));
373 fprintf(rpt, " old tree : %s\n", sha1_to_hex(b->branch_tree.versions[0].sha1));
374 fprintf(rpt, " cur tree : %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1));
375 fprintf(rpt, " commit clock: %" PRIuMAX "\n", b->last_commit);
377 fputs(" last pack : ", rpt);
378 if (b->pack_id < MAX_PACK_ID)
379 fprintf(rpt, "%u", b->pack_id);
380 fputc('\n', rpt);
382 fputc('\n', rpt);
385 static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *);
387 static void write_crash_report(const char *err)
389 char *loc = git_path("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
390 FILE *rpt = fopen(loc, "w");
391 struct branch *b;
392 unsigned long lu;
393 struct recent_command *rc;
395 if (!rpt) {
396 error("can't write crash report %s: %s", loc, strerror(errno));
397 return;
400 fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
402 fprintf(rpt, "fast-import crash report:\n");
403 fprintf(rpt, " fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
404 fprintf(rpt, " parent process : %"PRIuMAX"\n", (uintmax_t) getppid());
405 fprintf(rpt, " at %s\n", show_date(time(NULL), 0, DATE_LOCAL));
406 fputc('\n', rpt);
408 fputs("fatal: ", rpt);
409 fputs(err, rpt);
410 fputc('\n', rpt);
412 fputc('\n', rpt);
413 fputs("Most Recent Commands Before Crash\n", rpt);
414 fputs("---------------------------------\n", rpt);
415 for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
416 if (rc->next == &cmd_hist)
417 fputs("* ", rpt);
418 else
419 fputs(" ", rpt);
420 fputs(rc->buf, rpt);
421 fputc('\n', rpt);
424 fputc('\n', rpt);
425 fputs("Active Branch LRU\n", rpt);
426 fputs("-----------------\n", rpt);
427 fprintf(rpt, " active_branches = %lu cur, %lu max\n",
428 cur_active_branches,
429 max_active_branches);
430 fputc('\n', rpt);
431 fputs(" pos clock name\n", rpt);
432 fputs(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
433 for (b = active_branches, lu = 0; b; b = b->active_next_branch)
434 fprintf(rpt, " %2lu) %6" PRIuMAX" %s\n",
435 ++lu, b->last_commit, b->name);
437 fputc('\n', rpt);
438 fputs("Inactive Branches\n", rpt);
439 fputs("-----------------\n", rpt);
440 for (lu = 0; lu < branch_table_sz; lu++) {
441 for (b = branch_table[lu]; b; b = b->table_next_branch)
442 write_branch_report(rpt, b);
445 if (first_tag) {
446 struct tag *tg;
447 fputc('\n', rpt);
448 fputs("Annotated Tags\n", rpt);
449 fputs("--------------\n", rpt);
450 for (tg = first_tag; tg; tg = tg->next_tag) {
451 fputs(sha1_to_hex(tg->sha1), rpt);
452 fputc(' ', rpt);
453 fputs(tg->name, rpt);
454 fputc('\n', rpt);
458 fputc('\n', rpt);
459 fputs("Marks\n", rpt);
460 fputs("-----\n", rpt);
461 if (mark_file)
462 fprintf(rpt, " exported to %s\n", mark_file);
463 else
464 dump_marks_helper(rpt, 0, marks);
466 fputc('\n', rpt);
467 fputs("-------------------\n", rpt);
468 fputs("END OF CRASH REPORT\n", rpt);
469 fclose(rpt);
472 static void end_packfile(void);
473 static void unkeep_all_packs(void);
474 static void dump_marks(void);
476 static NORETURN void die_nicely(const char *err, va_list params)
478 static int zombie;
479 char message[2 * PATH_MAX];
481 vsnprintf(message, sizeof(message), err, params);
482 fputs("fatal: ", stderr);
483 fputs(message, stderr);
484 fputc('\n', stderr);
486 if (!zombie) {
487 zombie = 1;
488 write_crash_report(message);
489 end_packfile();
490 unkeep_all_packs();
491 dump_marks();
493 exit(128);
496 static void alloc_objects(unsigned int cnt)
498 struct object_entry_pool *b;
500 b = xmalloc(sizeof(struct object_entry_pool)
501 + cnt * sizeof(struct object_entry));
502 b->next_pool = blocks;
503 b->next_free = b->entries;
504 b->end = b->entries + cnt;
505 blocks = b;
506 alloc_count += cnt;
509 static struct object_entry *new_object(unsigned char *sha1)
511 struct object_entry *e;
513 if (blocks->next_free == blocks->end)
514 alloc_objects(object_entry_alloc);
516 e = blocks->next_free++;
517 hashcpy(e->sha1, sha1);
518 return e;
521 static struct object_entry *find_object(unsigned char *sha1)
523 unsigned int h = sha1[0] << 8 | sha1[1];
524 struct object_entry *e;
525 for (e = object_table[h]; e; e = e->next)
526 if (!hashcmp(sha1, e->sha1))
527 return e;
528 return NULL;
531 static struct object_entry *insert_object(unsigned char *sha1)
533 unsigned int h = sha1[0] << 8 | sha1[1];
534 struct object_entry *e = object_table[h];
535 struct object_entry *p = NULL;
537 while (e) {
538 if (!hashcmp(sha1, e->sha1))
539 return e;
540 p = e;
541 e = e->next;
544 e = new_object(sha1);
545 e->next = NULL;
546 e->offset = 0;
547 if (p)
548 p->next = e;
549 else
550 object_table[h] = e;
551 return e;
554 static unsigned int hc_str(const char *s, size_t len)
556 unsigned int r = 0;
557 while (len-- > 0)
558 r = r * 31 + *s++;
559 return r;
562 static void *pool_alloc(size_t len)
564 struct mem_pool *p;
565 void *r;
567 /* round up to a 'uintmax_t' alignment */
568 if (len & (sizeof(uintmax_t) - 1))
569 len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
571 for (p = mem_pool; p; p = p->next_pool)
572 if ((p->end - p->next_free >= len))
573 break;
575 if (!p) {
576 if (len >= (mem_pool_alloc/2)) {
577 total_allocd += len;
578 return xmalloc(len);
580 total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
581 p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc);
582 p->next_pool = mem_pool;
583 p->next_free = (char *) p->space;
584 p->end = p->next_free + mem_pool_alloc;
585 mem_pool = p;
588 r = p->next_free;
589 p->next_free += len;
590 return r;
593 static void *pool_calloc(size_t count, size_t size)
595 size_t len = count * size;
596 void *r = pool_alloc(len);
597 memset(r, 0, len);
598 return r;
601 static char *pool_strdup(const char *s)
603 char *r = pool_alloc(strlen(s) + 1);
604 strcpy(r, s);
605 return r;
608 static void insert_mark(uintmax_t idnum, struct object_entry *oe)
610 struct mark_set *s = marks;
611 while ((idnum >> s->shift) >= 1024) {
612 s = pool_calloc(1, sizeof(struct mark_set));
613 s->shift = marks->shift + 10;
614 s->data.sets[0] = marks;
615 marks = s;
617 while (s->shift) {
618 uintmax_t i = idnum >> s->shift;
619 idnum -= i << s->shift;
620 if (!s->data.sets[i]) {
621 s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
622 s->data.sets[i]->shift = s->shift - 10;
624 s = s->data.sets[i];
626 if (!s->data.marked[idnum])
627 marks_set_count++;
628 s->data.marked[idnum] = oe;
631 static struct object_entry *find_mark(uintmax_t idnum)
633 uintmax_t orig_idnum = idnum;
634 struct mark_set *s = marks;
635 struct object_entry *oe = NULL;
636 if ((idnum >> s->shift) < 1024) {
637 while (s && s->shift) {
638 uintmax_t i = idnum >> s->shift;
639 idnum -= i << s->shift;
640 s = s->data.sets[i];
642 if (s)
643 oe = s->data.marked[idnum];
645 if (!oe)
646 die("mark :%" PRIuMAX " not declared", orig_idnum);
647 return oe;
650 static struct atom_str *to_atom(const char *s, unsigned short len)
652 unsigned int hc = hc_str(s, len) % atom_table_sz;
653 struct atom_str *c;
655 for (c = atom_table[hc]; c; c = c->next_atom)
656 if (c->str_len == len && !strncmp(s, c->str_dat, len))
657 return c;
659 c = pool_alloc(sizeof(struct atom_str) + len + 1);
660 c->str_len = len;
661 strncpy(c->str_dat, s, len);
662 c->str_dat[len] = 0;
663 c->next_atom = atom_table[hc];
664 atom_table[hc] = c;
665 atom_cnt++;
666 return c;
669 static struct branch *lookup_branch(const char *name)
671 unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
672 struct branch *b;
674 for (b = branch_table[hc]; b; b = b->table_next_branch)
675 if (!strcmp(name, b->name))
676 return b;
677 return NULL;
680 static struct branch *new_branch(const char *name)
682 unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
683 struct branch *b = lookup_branch(name);
685 if (b)
686 die("Invalid attempt to create duplicate branch: %s", name);
687 switch (check_ref_format(name)) {
688 case 0: break; /* its valid */
689 case CHECK_REF_FORMAT_ONELEVEL:
690 break; /* valid, but too few '/', allow anyway */
691 default:
692 die("Branch name doesn't conform to GIT standards: %s", name);
695 b = pool_calloc(1, sizeof(struct branch));
696 b->name = pool_strdup(name);
697 b->table_next_branch = branch_table[hc];
698 b->branch_tree.versions[0].mode = S_IFDIR;
699 b->branch_tree.versions[1].mode = S_IFDIR;
700 b->active = 0;
701 b->pack_id = MAX_PACK_ID;
702 branch_table[hc] = b;
703 branch_count++;
704 return b;
707 static unsigned int hc_entries(unsigned int cnt)
709 cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
710 return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
713 static struct tree_content *new_tree_content(unsigned int cnt)
715 struct avail_tree_content *f, *l = NULL;
716 struct tree_content *t;
717 unsigned int hc = hc_entries(cnt);
719 for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
720 if (f->entry_capacity >= cnt)
721 break;
723 if (f) {
724 if (l)
725 l->next_avail = f->next_avail;
726 else
727 avail_tree_table[hc] = f->next_avail;
728 } else {
729 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
730 f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
731 f->entry_capacity = cnt;
734 t = (struct tree_content*)f;
735 t->entry_count = 0;
736 t->delta_depth = 0;
737 return t;
740 static void release_tree_entry(struct tree_entry *e);
741 static void release_tree_content(struct tree_content *t)
743 struct avail_tree_content *f = (struct avail_tree_content*)t;
744 unsigned int hc = hc_entries(f->entry_capacity);
745 f->next_avail = avail_tree_table[hc];
746 avail_tree_table[hc] = f;
749 static void release_tree_content_recursive(struct tree_content *t)
751 unsigned int i;
752 for (i = 0; i < t->entry_count; i++)
753 release_tree_entry(t->entries[i]);
754 release_tree_content(t);
757 static struct tree_content *grow_tree_content(
758 struct tree_content *t,
759 int amt)
761 struct tree_content *r = new_tree_content(t->entry_count + amt);
762 r->entry_count = t->entry_count;
763 r->delta_depth = t->delta_depth;
764 memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
765 release_tree_content(t);
766 return r;
769 static struct tree_entry *new_tree_entry(void)
771 struct tree_entry *e;
773 if (!avail_tree_entry) {
774 unsigned int n = tree_entry_alloc;
775 total_allocd += n * sizeof(struct tree_entry);
776 avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry));
777 while (n-- > 1) {
778 *((void**)e) = e + 1;
779 e++;
781 *((void**)e) = NULL;
784 e = avail_tree_entry;
785 avail_tree_entry = *((void**)e);
786 return e;
789 static void release_tree_entry(struct tree_entry *e)
791 if (e->tree)
792 release_tree_content_recursive(e->tree);
793 *((void**)e) = avail_tree_entry;
794 avail_tree_entry = e;
797 static struct tree_content *dup_tree_content(struct tree_content *s)
799 struct tree_content *d;
800 struct tree_entry *a, *b;
801 unsigned int i;
803 if (!s)
804 return NULL;
805 d = new_tree_content(s->entry_count);
806 for (i = 0; i < s->entry_count; i++) {
807 a = s->entries[i];
808 b = new_tree_entry();
809 memcpy(b, a, sizeof(*a));
810 if (a->tree && is_null_sha1(b->versions[1].sha1))
811 b->tree = dup_tree_content(a->tree);
812 else
813 b->tree = NULL;
814 d->entries[i] = b;
816 d->entry_count = s->entry_count;
817 d->delta_depth = s->delta_depth;
819 return d;
822 static void start_packfile(void)
824 static char tmpfile[PATH_MAX];
825 struct packed_git *p;
826 struct pack_header hdr;
827 int pack_fd;
829 pack_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
830 "pack/tmp_pack_XXXXXX");
831 p = xcalloc(1, sizeof(*p) + strlen(tmpfile) + 2);
832 strcpy(p->pack_name, tmpfile);
833 p->pack_fd = pack_fd;
835 hdr.hdr_signature = htonl(PACK_SIGNATURE);
836 hdr.hdr_version = htonl(2);
837 hdr.hdr_entries = 0;
838 write_or_die(p->pack_fd, &hdr, sizeof(hdr));
840 pack_data = p;
841 pack_size = sizeof(hdr);
842 object_count = 0;
844 all_packs = xrealloc(all_packs, sizeof(*all_packs) * (pack_id + 1));
845 all_packs[pack_id] = p;
848 static int oecmp (const void *a_, const void *b_)
850 struct object_entry *a = *((struct object_entry**)a_);
851 struct object_entry *b = *((struct object_entry**)b_);
852 return hashcmp(a->sha1, b->sha1);
855 static char *create_index(void)
857 static char tmpfile[PATH_MAX];
858 git_SHA_CTX ctx;
859 struct sha1file *f;
860 struct object_entry **idx, **c, **last, *e;
861 struct object_entry_pool *o;
862 uint32_t array[256];
863 int i, idx_fd;
865 /* Build the sorted table of object IDs. */
866 idx = xmalloc(object_count * sizeof(struct object_entry*));
867 c = idx;
868 for (o = blocks; o; o = o->next_pool)
869 for (e = o->next_free; e-- != o->entries;)
870 if (pack_id == e->pack_id)
871 *c++ = e;
872 last = idx + object_count;
873 if (c != last)
874 die("internal consistency error creating the index");
875 qsort(idx, object_count, sizeof(struct object_entry*), oecmp);
877 /* Generate the fan-out array. */
878 c = idx;
879 for (i = 0; i < 256; i++) {
880 struct object_entry **next = c;
881 while (next < last) {
882 if ((*next)->sha1[0] != i)
883 break;
884 next++;
886 array[i] = htonl(next - idx);
887 c = next;
890 idx_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
891 "pack/tmp_idx_XXXXXX");
892 f = sha1fd(idx_fd, tmpfile);
893 sha1write(f, array, 256 * sizeof(int));
894 git_SHA1_Init(&ctx);
895 for (c = idx; c != last; c++) {
896 uint32_t offset = htonl((*c)->offset);
897 sha1write(f, &offset, 4);
898 sha1write(f, (*c)->sha1, sizeof((*c)->sha1));
899 git_SHA1_Update(&ctx, (*c)->sha1, 20);
901 sha1write(f, pack_data->sha1, sizeof(pack_data->sha1));
902 sha1close(f, NULL, CSUM_FSYNC);
903 free(idx);
904 git_SHA1_Final(pack_data->sha1, &ctx);
905 return tmpfile;
908 static char *keep_pack(char *curr_index_name)
910 static char name[PATH_MAX];
911 static const char *keep_msg = "fast-import";
912 int keep_fd;
914 keep_fd = odb_pack_keep(name, sizeof(name), pack_data->sha1);
915 if (keep_fd < 0)
916 die_errno("cannot create keep file");
917 write_or_die(keep_fd, keep_msg, strlen(keep_msg));
918 if (close(keep_fd))
919 die_errno("failed to write keep file");
921 snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
922 get_object_directory(), sha1_to_hex(pack_data->sha1));
923 if (move_temp_to_file(pack_data->pack_name, name))
924 die("cannot store pack file");
926 snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
927 get_object_directory(), sha1_to_hex(pack_data->sha1));
928 if (move_temp_to_file(curr_index_name, name))
929 die("cannot store index file");
930 return name;
933 static void unkeep_all_packs(void)
935 static char name[PATH_MAX];
936 int k;
938 for (k = 0; k < pack_id; k++) {
939 struct packed_git *p = all_packs[k];
940 snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
941 get_object_directory(), sha1_to_hex(p->sha1));
942 unlink_or_warn(name);
946 static void end_packfile(void)
948 struct packed_git *old_p = pack_data, *new_p;
950 clear_delta_base_cache();
951 if (object_count) {
952 char *idx_name;
953 int i;
954 struct branch *b;
955 struct tag *t;
957 close_pack_windows(pack_data);
958 fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
959 pack_data->pack_name, object_count,
960 NULL, 0);
961 close(pack_data->pack_fd);
962 idx_name = keep_pack(create_index());
964 /* Register the packfile with core git's machinery. */
965 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
966 if (!new_p)
967 die("core git rejected index %s", idx_name);
968 all_packs[pack_id] = new_p;
969 install_packed_git(new_p);
971 /* Print the boundary */
972 if (pack_edges) {
973 fprintf(pack_edges, "%s:", new_p->pack_name);
974 for (i = 0; i < branch_table_sz; i++) {
975 for (b = branch_table[i]; b; b = b->table_next_branch) {
976 if (b->pack_id == pack_id)
977 fprintf(pack_edges, " %s", sha1_to_hex(b->sha1));
980 for (t = first_tag; t; t = t->next_tag) {
981 if (t->pack_id == pack_id)
982 fprintf(pack_edges, " %s", sha1_to_hex(t->sha1));
984 fputc('\n', pack_edges);
985 fflush(pack_edges);
988 pack_id++;
990 else {
991 close(old_p->pack_fd);
992 unlink_or_warn(old_p->pack_name);
994 free(old_p);
996 /* We can't carry a delta across packfiles. */
997 strbuf_release(&last_blob.data);
998 last_blob.offset = 0;
999 last_blob.depth = 0;
1002 static void cycle_packfile(void)
1004 end_packfile();
1005 start_packfile();
1008 static size_t encode_header(
1009 enum object_type type,
1010 size_t size,
1011 unsigned char *hdr)
1013 int n = 1;
1014 unsigned char c;
1016 if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
1017 die("bad type %d", type);
1019 c = (type << 4) | (size & 15);
1020 size >>= 4;
1021 while (size) {
1022 *hdr++ = c | 0x80;
1023 c = size & 0x7f;
1024 size >>= 7;
1025 n++;
1027 *hdr = c;
1028 return n;
1031 static int store_object(
1032 enum object_type type,
1033 struct strbuf *dat,
1034 struct last_object *last,
1035 unsigned char *sha1out,
1036 uintmax_t mark)
1038 void *out, *delta;
1039 struct object_entry *e;
1040 unsigned char hdr[96];
1041 unsigned char sha1[20];
1042 unsigned long hdrlen, deltalen;
1043 git_SHA_CTX c;
1044 z_stream s;
1046 hdrlen = sprintf((char *)hdr,"%s %lu", typename(type),
1047 (unsigned long)dat->len) + 1;
1048 git_SHA1_Init(&c);
1049 git_SHA1_Update(&c, hdr, hdrlen);
1050 git_SHA1_Update(&c, dat->buf, dat->len);
1051 git_SHA1_Final(sha1, &c);
1052 if (sha1out)
1053 hashcpy(sha1out, sha1);
1055 e = insert_object(sha1);
1056 if (mark)
1057 insert_mark(mark, e);
1058 if (e->offset) {
1059 duplicate_count_by_type[type]++;
1060 return 1;
1061 } else if (find_sha1_pack(sha1, packed_git)) {
1062 e->type = type;
1063 e->pack_id = MAX_PACK_ID;
1064 e->offset = 1; /* just not zero! */
1065 duplicate_count_by_type[type]++;
1066 return 1;
1069 if (last && last->data.buf && last->depth < max_depth) {
1070 delta = diff_delta(last->data.buf, last->data.len,
1071 dat->buf, dat->len,
1072 &deltalen, 0);
1073 if (delta && deltalen >= dat->len) {
1074 free(delta);
1075 delta = NULL;
1077 } else
1078 delta = NULL;
1080 memset(&s, 0, sizeof(s));
1081 deflateInit(&s, pack_compression_level);
1082 if (delta) {
1083 s.next_in = delta;
1084 s.avail_in = deltalen;
1085 } else {
1086 s.next_in = (void *)dat->buf;
1087 s.avail_in = dat->len;
1089 s.avail_out = deflateBound(&s, s.avail_in);
1090 s.next_out = out = xmalloc(s.avail_out);
1091 while (deflate(&s, Z_FINISH) == Z_OK)
1092 /* nothing */;
1093 deflateEnd(&s);
1095 /* Determine if we should auto-checkpoint. */
1096 if ((pack_size + 60 + s.total_out) > max_packsize
1097 || (pack_size + 60 + s.total_out) < pack_size) {
1099 /* This new object needs to *not* have the current pack_id. */
1100 e->pack_id = pack_id + 1;
1101 cycle_packfile();
1103 /* We cannot carry a delta into the new pack. */
1104 if (delta) {
1105 free(delta);
1106 delta = NULL;
1108 memset(&s, 0, sizeof(s));
1109 deflateInit(&s, pack_compression_level);
1110 s.next_in = (void *)dat->buf;
1111 s.avail_in = dat->len;
1112 s.avail_out = deflateBound(&s, s.avail_in);
1113 s.next_out = out = xrealloc(out, s.avail_out);
1114 while (deflate(&s, Z_FINISH) == Z_OK)
1115 /* nothing */;
1116 deflateEnd(&s);
1120 e->type = type;
1121 e->pack_id = pack_id;
1122 e->offset = pack_size;
1123 object_count++;
1124 object_count_by_type[type]++;
1126 if (delta) {
1127 unsigned long ofs = e->offset - last->offset;
1128 unsigned pos = sizeof(hdr) - 1;
1130 delta_count_by_type[type]++;
1131 e->depth = last->depth + 1;
1133 hdrlen = encode_header(OBJ_OFS_DELTA, deltalen, hdr);
1134 write_or_die(pack_data->pack_fd, hdr, hdrlen);
1135 pack_size += hdrlen;
1137 hdr[pos] = ofs & 127;
1138 while (ofs >>= 7)
1139 hdr[--pos] = 128 | (--ofs & 127);
1140 write_or_die(pack_data->pack_fd, hdr + pos, sizeof(hdr) - pos);
1141 pack_size += sizeof(hdr) - pos;
1142 } else {
1143 e->depth = 0;
1144 hdrlen = encode_header(type, dat->len, hdr);
1145 write_or_die(pack_data->pack_fd, hdr, hdrlen);
1146 pack_size += hdrlen;
1149 write_or_die(pack_data->pack_fd, out, s.total_out);
1150 pack_size += s.total_out;
1152 free(out);
1153 free(delta);
1154 if (last) {
1155 if (last->no_swap) {
1156 last->data = *dat;
1157 } else {
1158 strbuf_swap(&last->data, dat);
1160 last->offset = e->offset;
1161 last->depth = e->depth;
1163 return 0;
1166 /* All calls must be guarded by find_object() or find_mark() to
1167 * ensure the 'struct object_entry' passed was written by this
1168 * process instance. We unpack the entry by the offset, avoiding
1169 * the need for the corresponding .idx file. This unpacking rule
1170 * works because we only use OBJ_REF_DELTA within the packfiles
1171 * created by fast-import.
1173 * oe must not be NULL. Such an oe usually comes from giving
1174 * an unknown SHA-1 to find_object() or an undefined mark to
1175 * find_mark(). Callers must test for this condition and use
1176 * the standard read_sha1_file() when it happens.
1178 * oe->pack_id must not be MAX_PACK_ID. Such an oe is usually from
1179 * find_mark(), where the mark was reloaded from an existing marks
1180 * file and is referencing an object that this fast-import process
1181 * instance did not write out to a packfile. Callers must test for
1182 * this condition and use read_sha1_file() instead.
1184 static void *gfi_unpack_entry(
1185 struct object_entry *oe,
1186 unsigned long *sizep)
1188 enum object_type type;
1189 struct packed_git *p = all_packs[oe->pack_id];
1190 if (p == pack_data && p->pack_size < (pack_size + 20)) {
1191 /* The object is stored in the packfile we are writing to
1192 * and we have modified it since the last time we scanned
1193 * back to read a previously written object. If an old
1194 * window covered [p->pack_size, p->pack_size + 20) its
1195 * data is stale and is not valid. Closing all windows
1196 * and updating the packfile length ensures we can read
1197 * the newly written data.
1199 close_pack_windows(p);
1201 /* We have to offer 20 bytes additional on the end of
1202 * the packfile as the core unpacker code assumes the
1203 * footer is present at the file end and must promise
1204 * at least 20 bytes within any window it maps. But
1205 * we don't actually create the footer here.
1207 p->pack_size = pack_size + 20;
1209 return unpack_entry(p, oe->offset, &type, sizep);
1212 static const char *get_mode(const char *str, uint16_t *modep)
1214 unsigned char c;
1215 uint16_t mode = 0;
1217 while ((c = *str++) != ' ') {
1218 if (c < '0' || c > '7')
1219 return NULL;
1220 mode = (mode << 3) + (c - '0');
1222 *modep = mode;
1223 return str;
1226 static void load_tree(struct tree_entry *root)
1228 unsigned char *sha1 = root->versions[1].sha1;
1229 struct object_entry *myoe;
1230 struct tree_content *t;
1231 unsigned long size;
1232 char *buf;
1233 const char *c;
1235 root->tree = t = new_tree_content(8);
1236 if (is_null_sha1(sha1))
1237 return;
1239 myoe = find_object(sha1);
1240 if (myoe && myoe->pack_id != MAX_PACK_ID) {
1241 if (myoe->type != OBJ_TREE)
1242 die("Not a tree: %s", sha1_to_hex(sha1));
1243 t->delta_depth = myoe->depth;
1244 buf = gfi_unpack_entry(myoe, &size);
1245 if (!buf)
1246 die("Can't load tree %s", sha1_to_hex(sha1));
1247 } else {
1248 enum object_type type;
1249 buf = read_sha1_file(sha1, &type, &size);
1250 if (!buf || type != OBJ_TREE)
1251 die("Can't load tree %s", sha1_to_hex(sha1));
1254 c = buf;
1255 while (c != (buf + size)) {
1256 struct tree_entry *e = new_tree_entry();
1258 if (t->entry_count == t->entry_capacity)
1259 root->tree = t = grow_tree_content(t, t->entry_count);
1260 t->entries[t->entry_count++] = e;
1262 e->tree = NULL;
1263 c = get_mode(c, &e->versions[1].mode);
1264 if (!c)
1265 die("Corrupt mode in %s", sha1_to_hex(sha1));
1266 e->versions[0].mode = e->versions[1].mode;
1267 e->name = to_atom(c, strlen(c));
1268 c += e->name->str_len + 1;
1269 hashcpy(e->versions[0].sha1, (unsigned char *)c);
1270 hashcpy(e->versions[1].sha1, (unsigned char *)c);
1271 c += 20;
1273 free(buf);
1276 static int tecmp0 (const void *_a, const void *_b)
1278 struct tree_entry *a = *((struct tree_entry**)_a);
1279 struct tree_entry *b = *((struct tree_entry**)_b);
1280 return base_name_compare(
1281 a->name->str_dat, a->name->str_len, a->versions[0].mode,
1282 b->name->str_dat, b->name->str_len, b->versions[0].mode);
1285 static int tecmp1 (const void *_a, const void *_b)
1287 struct tree_entry *a = *((struct tree_entry**)_a);
1288 struct tree_entry *b = *((struct tree_entry**)_b);
1289 return base_name_compare(
1290 a->name->str_dat, a->name->str_len, a->versions[1].mode,
1291 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1294 static void mktree(struct tree_content *t, int v, struct strbuf *b)
1296 size_t maxlen = 0;
1297 unsigned int i;
1299 if (!v)
1300 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0);
1301 else
1302 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1);
1304 for (i = 0; i < t->entry_count; i++) {
1305 if (t->entries[i]->versions[v].mode)
1306 maxlen += t->entries[i]->name->str_len + 34;
1309 strbuf_reset(b);
1310 strbuf_grow(b, maxlen);
1311 for (i = 0; i < t->entry_count; i++) {
1312 struct tree_entry *e = t->entries[i];
1313 if (!e->versions[v].mode)
1314 continue;
1315 strbuf_addf(b, "%o %s%c", (unsigned int)e->versions[v].mode,
1316 e->name->str_dat, '\0');
1317 strbuf_add(b, e->versions[v].sha1, 20);
1321 static void store_tree(struct tree_entry *root)
1323 struct tree_content *t = root->tree;
1324 unsigned int i, j, del;
1325 struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1326 struct object_entry *le;
1328 if (!is_null_sha1(root->versions[1].sha1))
1329 return;
1331 for (i = 0; i < t->entry_count; i++) {
1332 if (t->entries[i]->tree)
1333 store_tree(t->entries[i]);
1336 le = find_object(root->versions[0].sha1);
1337 if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1338 mktree(t, 0, &old_tree);
1339 lo.data = old_tree;
1340 lo.offset = le->offset;
1341 lo.depth = t->delta_depth;
1344 mktree(t, 1, &new_tree);
1345 store_object(OBJ_TREE, &new_tree, &lo, root->versions[1].sha1, 0);
1347 t->delta_depth = lo.depth;
1348 for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1349 struct tree_entry *e = t->entries[i];
1350 if (e->versions[1].mode) {
1351 e->versions[0].mode = e->versions[1].mode;
1352 hashcpy(e->versions[0].sha1, e->versions[1].sha1);
1353 t->entries[j++] = e;
1354 } else {
1355 release_tree_entry(e);
1356 del++;
1359 t->entry_count -= del;
1362 static int tree_content_set(
1363 struct tree_entry *root,
1364 const char *p,
1365 const unsigned char *sha1,
1366 const uint16_t mode,
1367 struct tree_content *subtree)
1369 struct tree_content *t = root->tree;
1370 const char *slash1;
1371 unsigned int i, n;
1372 struct tree_entry *e;
1374 slash1 = strchr(p, '/');
1375 if (slash1)
1376 n = slash1 - p;
1377 else
1378 n = strlen(p);
1379 if (!n)
1380 die("Empty path component found in input");
1381 if (!slash1 && !S_ISDIR(mode) && subtree)
1382 die("Non-directories cannot have subtrees");
1384 for (i = 0; i < t->entry_count; i++) {
1385 e = t->entries[i];
1386 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1387 if (!slash1) {
1388 if (!S_ISDIR(mode)
1389 && e->versions[1].mode == mode
1390 && !hashcmp(e->versions[1].sha1, sha1))
1391 return 0;
1392 e->versions[1].mode = mode;
1393 hashcpy(e->versions[1].sha1, sha1);
1394 if (e->tree)
1395 release_tree_content_recursive(e->tree);
1396 e->tree = subtree;
1397 hashclr(root->versions[1].sha1);
1398 return 1;
1400 if (!S_ISDIR(e->versions[1].mode)) {
1401 e->tree = new_tree_content(8);
1402 e->versions[1].mode = S_IFDIR;
1404 if (!e->tree)
1405 load_tree(e);
1406 if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) {
1407 hashclr(root->versions[1].sha1);
1408 return 1;
1410 return 0;
1414 if (t->entry_count == t->entry_capacity)
1415 root->tree = t = grow_tree_content(t, t->entry_count);
1416 e = new_tree_entry();
1417 e->name = to_atom(p, n);
1418 e->versions[0].mode = 0;
1419 hashclr(e->versions[0].sha1);
1420 t->entries[t->entry_count++] = e;
1421 if (slash1) {
1422 e->tree = new_tree_content(8);
1423 e->versions[1].mode = S_IFDIR;
1424 tree_content_set(e, slash1 + 1, sha1, mode, subtree);
1425 } else {
1426 e->tree = subtree;
1427 e->versions[1].mode = mode;
1428 hashcpy(e->versions[1].sha1, sha1);
1430 hashclr(root->versions[1].sha1);
1431 return 1;
1434 static int tree_content_remove(
1435 struct tree_entry *root,
1436 const char *p,
1437 struct tree_entry *backup_leaf)
1439 struct tree_content *t = root->tree;
1440 const char *slash1;
1441 unsigned int i, n;
1442 struct tree_entry *e;
1444 slash1 = strchr(p, '/');
1445 if (slash1)
1446 n = slash1 - p;
1447 else
1448 n = strlen(p);
1450 for (i = 0; i < t->entry_count; i++) {
1451 e = t->entries[i];
1452 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1453 if (!slash1 || !S_ISDIR(e->versions[1].mode))
1454 goto del_entry;
1455 if (!e->tree)
1456 load_tree(e);
1457 if (tree_content_remove(e, slash1 + 1, backup_leaf)) {
1458 for (n = 0; n < e->tree->entry_count; n++) {
1459 if (e->tree->entries[n]->versions[1].mode) {
1460 hashclr(root->versions[1].sha1);
1461 return 1;
1464 backup_leaf = NULL;
1465 goto del_entry;
1467 return 0;
1470 return 0;
1472 del_entry:
1473 if (backup_leaf)
1474 memcpy(backup_leaf, e, sizeof(*backup_leaf));
1475 else if (e->tree)
1476 release_tree_content_recursive(e->tree);
1477 e->tree = NULL;
1478 e->versions[1].mode = 0;
1479 hashclr(e->versions[1].sha1);
1480 hashclr(root->versions[1].sha1);
1481 return 1;
1484 static int tree_content_get(
1485 struct tree_entry *root,
1486 const char *p,
1487 struct tree_entry *leaf)
1489 struct tree_content *t = root->tree;
1490 const char *slash1;
1491 unsigned int i, n;
1492 struct tree_entry *e;
1494 slash1 = strchr(p, '/');
1495 if (slash1)
1496 n = slash1 - p;
1497 else
1498 n = strlen(p);
1500 for (i = 0; i < t->entry_count; i++) {
1501 e = t->entries[i];
1502 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1503 if (!slash1) {
1504 memcpy(leaf, e, sizeof(*leaf));
1505 if (e->tree && is_null_sha1(e->versions[1].sha1))
1506 leaf->tree = dup_tree_content(e->tree);
1507 else
1508 leaf->tree = NULL;
1509 return 1;
1511 if (!S_ISDIR(e->versions[1].mode))
1512 return 0;
1513 if (!e->tree)
1514 load_tree(e);
1515 return tree_content_get(e, slash1 + 1, leaf);
1518 return 0;
1521 static int update_branch(struct branch *b)
1523 static const char *msg = "fast-import";
1524 struct ref_lock *lock;
1525 unsigned char old_sha1[20];
1527 if (is_null_sha1(b->sha1))
1528 return 0;
1529 if (read_ref(b->name, old_sha1))
1530 hashclr(old_sha1);
1531 lock = lock_any_ref_for_update(b->name, old_sha1, 0);
1532 if (!lock)
1533 return error("Unable to lock %s", b->name);
1534 if (!force_update && !is_null_sha1(old_sha1)) {
1535 struct commit *old_cmit, *new_cmit;
1537 old_cmit = lookup_commit_reference_gently(old_sha1, 0);
1538 new_cmit = lookup_commit_reference_gently(b->sha1, 0);
1539 if (!old_cmit || !new_cmit) {
1540 unlock_ref(lock);
1541 return error("Branch %s is missing commits.", b->name);
1544 if (!in_merge_bases(old_cmit, &new_cmit, 1)) {
1545 unlock_ref(lock);
1546 warning("Not updating %s"
1547 " (new tip %s does not contain %s)",
1548 b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1));
1549 return -1;
1552 if (write_ref_sha1(lock, b->sha1, msg) < 0)
1553 return error("Unable to update %s", b->name);
1554 return 0;
1557 static void dump_branches(void)
1559 unsigned int i;
1560 struct branch *b;
1562 for (i = 0; i < branch_table_sz; i++) {
1563 for (b = branch_table[i]; b; b = b->table_next_branch)
1564 failure |= update_branch(b);
1568 static void dump_tags(void)
1570 static const char *msg = "fast-import";
1571 struct tag *t;
1572 struct ref_lock *lock;
1573 char ref_name[PATH_MAX];
1575 for (t = first_tag; t; t = t->next_tag) {
1576 sprintf(ref_name, "tags/%s", t->name);
1577 lock = lock_ref_sha1(ref_name, NULL);
1578 if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
1579 failure |= error("Unable to update %s", ref_name);
1583 static void dump_marks_helper(FILE *f,
1584 uintmax_t base,
1585 struct mark_set *m)
1587 uintmax_t k;
1588 if (m->shift) {
1589 for (k = 0; k < 1024; k++) {
1590 if (m->data.sets[k])
1591 dump_marks_helper(f, (base + k) << m->shift,
1592 m->data.sets[k]);
1594 } else {
1595 for (k = 0; k < 1024; k++) {
1596 if (m->data.marked[k])
1597 fprintf(f, ":%" PRIuMAX " %s\n", base + k,
1598 sha1_to_hex(m->data.marked[k]->sha1));
1603 static void dump_marks(void)
1605 static struct lock_file mark_lock;
1606 int mark_fd;
1607 FILE *f;
1609 if (!mark_file)
1610 return;
1612 mark_fd = hold_lock_file_for_update(&mark_lock, mark_file, 0);
1613 if (mark_fd < 0) {
1614 failure |= error("Unable to write marks file %s: %s",
1615 mark_file, strerror(errno));
1616 return;
1619 f = fdopen(mark_fd, "w");
1620 if (!f) {
1621 int saved_errno = errno;
1622 rollback_lock_file(&mark_lock);
1623 failure |= error("Unable to write marks file %s: %s",
1624 mark_file, strerror(saved_errno));
1625 return;
1629 * Since the lock file was fdopen()'ed, it should not be close()'ed.
1630 * Assign -1 to the lock file descriptor so that commit_lock_file()
1631 * won't try to close() it.
1633 mark_lock.fd = -1;
1635 dump_marks_helper(f, 0, marks);
1636 if (ferror(f) || fclose(f)) {
1637 int saved_errno = errno;
1638 rollback_lock_file(&mark_lock);
1639 failure |= error("Unable to write marks file %s: %s",
1640 mark_file, strerror(saved_errno));
1641 return;
1644 if (commit_lock_file(&mark_lock)) {
1645 int saved_errno = errno;
1646 rollback_lock_file(&mark_lock);
1647 failure |= error("Unable to commit marks file %s: %s",
1648 mark_file, strerror(saved_errno));
1649 return;
1653 static void read_marks(void)
1655 char line[512];
1656 FILE *f = fopen(input_file, "r");
1657 if (!f)
1658 die_errno("cannot read '%s'", input_file);
1659 while (fgets(line, sizeof(line), f)) {
1660 uintmax_t mark;
1661 char *end;
1662 unsigned char sha1[20];
1663 struct object_entry *e;
1665 end = strchr(line, '\n');
1666 if (line[0] != ':' || !end)
1667 die("corrupt mark line: %s", line);
1668 *end = 0;
1669 mark = strtoumax(line + 1, &end, 10);
1670 if (!mark || end == line + 1
1671 || *end != ' ' || get_sha1(end + 1, sha1))
1672 die("corrupt mark line: %s", line);
1673 e = find_object(sha1);
1674 if (!e) {
1675 enum object_type type = sha1_object_info(sha1, NULL);
1676 if (type < 0)
1677 die("object not found: %s", sha1_to_hex(sha1));
1678 e = insert_object(sha1);
1679 e->type = type;
1680 e->pack_id = MAX_PACK_ID;
1681 e->offset = 1; /* just not zero! */
1683 insert_mark(mark, e);
1685 fclose(f);
1689 static int read_next_command(void)
1691 static int stdin_eof = 0;
1693 if (stdin_eof) {
1694 unread_command_buf = 0;
1695 return EOF;
1698 do {
1699 if (unread_command_buf) {
1700 unread_command_buf = 0;
1701 } else {
1702 struct recent_command *rc;
1704 strbuf_detach(&command_buf, NULL);
1705 stdin_eof = strbuf_getline(&command_buf, stdin, '\n');
1706 if (stdin_eof)
1707 return EOF;
1709 if (!seen_non_option_command
1710 && prefixcmp(command_buf.buf, "feature ")
1711 && prefixcmp(command_buf.buf, "option ")) {
1712 parse_argv();
1715 rc = rc_free;
1716 if (rc)
1717 rc_free = rc->next;
1718 else {
1719 rc = cmd_hist.next;
1720 cmd_hist.next = rc->next;
1721 cmd_hist.next->prev = &cmd_hist;
1722 free(rc->buf);
1725 rc->buf = command_buf.buf;
1726 rc->prev = cmd_tail;
1727 rc->next = cmd_hist.prev;
1728 rc->prev->next = rc;
1729 cmd_tail = rc;
1731 } while (command_buf.buf[0] == '#');
1733 return 0;
1736 static void skip_optional_lf(void)
1738 int term_char = fgetc(stdin);
1739 if (term_char != '\n' && term_char != EOF)
1740 ungetc(term_char, stdin);
1743 static void parse_mark(void)
1745 if (!prefixcmp(command_buf.buf, "mark :")) {
1746 next_mark = strtoumax(command_buf.buf + 6, NULL, 10);
1747 read_next_command();
1749 else
1750 next_mark = 0;
1753 static void parse_data(struct strbuf *sb)
1755 strbuf_reset(sb);
1757 if (prefixcmp(command_buf.buf, "data "))
1758 die("Expected 'data n' command, found: %s", command_buf.buf);
1760 if (!prefixcmp(command_buf.buf + 5, "<<")) {
1761 char *term = xstrdup(command_buf.buf + 5 + 2);
1762 size_t term_len = command_buf.len - 5 - 2;
1764 strbuf_detach(&command_buf, NULL);
1765 for (;;) {
1766 if (strbuf_getline(&command_buf, stdin, '\n') == EOF)
1767 die("EOF in data (terminator '%s' not found)", term);
1768 if (term_len == command_buf.len
1769 && !strcmp(term, command_buf.buf))
1770 break;
1771 strbuf_addbuf(sb, &command_buf);
1772 strbuf_addch(sb, '\n');
1774 free(term);
1776 else {
1777 size_t n = 0, length;
1779 length = strtoul(command_buf.buf + 5, NULL, 10);
1781 while (n < length) {
1782 size_t s = strbuf_fread(sb, length - n, stdin);
1783 if (!s && feof(stdin))
1784 die("EOF in data (%lu bytes remaining)",
1785 (unsigned long)(length - n));
1786 n += s;
1790 skip_optional_lf();
1793 static int validate_raw_date(const char *src, char *result, int maxlen)
1795 const char *orig_src = src;
1796 char *endp;
1798 errno = 0;
1800 strtoul(src, &endp, 10);
1801 if (errno || endp == src || *endp != ' ')
1802 return -1;
1804 src = endp + 1;
1805 if (*src != '-' && *src != '+')
1806 return -1;
1808 strtoul(src + 1, &endp, 10);
1809 if (errno || endp == src || *endp || (endp - orig_src) >= maxlen)
1810 return -1;
1812 strcpy(result, orig_src);
1813 return 0;
1816 static char *parse_ident(const char *buf)
1818 const char *gt;
1819 size_t name_len;
1820 char *ident;
1822 gt = strrchr(buf, '>');
1823 if (!gt)
1824 die("Missing > in ident string: %s", buf);
1825 gt++;
1826 if (*gt != ' ')
1827 die("Missing space after > in ident string: %s", buf);
1828 gt++;
1829 name_len = gt - buf;
1830 ident = xmalloc(name_len + 24);
1831 strncpy(ident, buf, name_len);
1833 switch (whenspec) {
1834 case WHENSPEC_RAW:
1835 if (validate_raw_date(gt, ident + name_len, 24) < 0)
1836 die("Invalid raw date \"%s\" in ident: %s", gt, buf);
1837 break;
1838 case WHENSPEC_RFC2822:
1839 if (parse_date(gt, ident + name_len, 24) < 0)
1840 die("Invalid rfc2822 date \"%s\" in ident: %s", gt, buf);
1841 break;
1842 case WHENSPEC_NOW:
1843 if (strcmp("now", gt))
1844 die("Date in ident must be 'now': %s", buf);
1845 datestamp(ident + name_len, 24);
1846 break;
1849 return ident;
1852 static void parse_new_blob(void)
1854 static struct strbuf buf = STRBUF_INIT;
1856 read_next_command();
1857 parse_mark();
1858 parse_data(&buf);
1859 store_object(OBJ_BLOB, &buf, &last_blob, NULL, next_mark);
1862 static void unload_one_branch(void)
1864 while (cur_active_branches
1865 && cur_active_branches >= max_active_branches) {
1866 uintmax_t min_commit = ULONG_MAX;
1867 struct branch *e, *l = NULL, *p = NULL;
1869 for (e = active_branches; e; e = e->active_next_branch) {
1870 if (e->last_commit < min_commit) {
1871 p = l;
1872 min_commit = e->last_commit;
1874 l = e;
1877 if (p) {
1878 e = p->active_next_branch;
1879 p->active_next_branch = e->active_next_branch;
1880 } else {
1881 e = active_branches;
1882 active_branches = e->active_next_branch;
1884 e->active = 0;
1885 e->active_next_branch = NULL;
1886 if (e->branch_tree.tree) {
1887 release_tree_content_recursive(e->branch_tree.tree);
1888 e->branch_tree.tree = NULL;
1890 cur_active_branches--;
1894 static void load_branch(struct branch *b)
1896 load_tree(&b->branch_tree);
1897 if (!b->active) {
1898 b->active = 1;
1899 b->active_next_branch = active_branches;
1900 active_branches = b;
1901 cur_active_branches++;
1902 branch_load_count++;
1906 static void file_change_m(struct branch *b)
1908 const char *p = command_buf.buf + 2;
1909 static struct strbuf uq = STRBUF_INIT;
1910 const char *endp;
1911 struct object_entry *oe = oe;
1912 unsigned char sha1[20];
1913 uint16_t mode, inline_data = 0;
1915 p = get_mode(p, &mode);
1916 if (!p)
1917 die("Corrupt mode: %s", command_buf.buf);
1918 switch (mode) {
1919 case 0644:
1920 case 0755:
1921 mode |= S_IFREG;
1922 case S_IFREG | 0644:
1923 case S_IFREG | 0755:
1924 case S_IFLNK:
1925 case S_IFGITLINK:
1926 /* ok */
1927 break;
1928 default:
1929 die("Corrupt mode: %s", command_buf.buf);
1932 if (*p == ':') {
1933 char *x;
1934 oe = find_mark(strtoumax(p + 1, &x, 10));
1935 hashcpy(sha1, oe->sha1);
1936 p = x;
1937 } else if (!prefixcmp(p, "inline")) {
1938 inline_data = 1;
1939 p += 6;
1940 } else {
1941 if (get_sha1_hex(p, sha1))
1942 die("Invalid SHA1: %s", command_buf.buf);
1943 oe = find_object(sha1);
1944 p += 40;
1946 if (*p++ != ' ')
1947 die("Missing space after SHA1: %s", command_buf.buf);
1949 strbuf_reset(&uq);
1950 if (!unquote_c_style(&uq, p, &endp)) {
1951 if (*endp)
1952 die("Garbage after path in: %s", command_buf.buf);
1953 p = uq.buf;
1956 if (S_ISGITLINK(mode)) {
1957 if (inline_data)
1958 die("Git links cannot be specified 'inline': %s",
1959 command_buf.buf);
1960 else if (oe) {
1961 if (oe->type != OBJ_COMMIT)
1962 die("Not a commit (actually a %s): %s",
1963 typename(oe->type), command_buf.buf);
1966 * Accept the sha1 without checking; it expected to be in
1967 * another repository.
1969 } else if (inline_data) {
1970 static struct strbuf buf = STRBUF_INIT;
1972 if (p != uq.buf) {
1973 strbuf_addstr(&uq, p);
1974 p = uq.buf;
1976 read_next_command();
1977 parse_data(&buf);
1978 store_object(OBJ_BLOB, &buf, &last_blob, sha1, 0);
1979 } else if (oe) {
1980 if (oe->type != OBJ_BLOB)
1981 die("Not a blob (actually a %s): %s",
1982 typename(oe->type), command_buf.buf);
1983 } else {
1984 enum object_type type = sha1_object_info(sha1, NULL);
1985 if (type < 0)
1986 die("Blob not found: %s", command_buf.buf);
1987 if (type != OBJ_BLOB)
1988 die("Not a blob (actually a %s): %s",
1989 typename(type), command_buf.buf);
1992 tree_content_set(&b->branch_tree, p, sha1, mode, NULL);
1995 static void file_change_d(struct branch *b)
1997 const char *p = command_buf.buf + 2;
1998 static struct strbuf uq = STRBUF_INIT;
1999 const char *endp;
2001 strbuf_reset(&uq);
2002 if (!unquote_c_style(&uq, p, &endp)) {
2003 if (*endp)
2004 die("Garbage after path in: %s", command_buf.buf);
2005 p = uq.buf;
2007 tree_content_remove(&b->branch_tree, p, NULL);
2010 static void file_change_cr(struct branch *b, int rename)
2012 const char *s, *d;
2013 static struct strbuf s_uq = STRBUF_INIT;
2014 static struct strbuf d_uq = STRBUF_INIT;
2015 const char *endp;
2016 struct tree_entry leaf;
2018 s = command_buf.buf + 2;
2019 strbuf_reset(&s_uq);
2020 if (!unquote_c_style(&s_uq, s, &endp)) {
2021 if (*endp != ' ')
2022 die("Missing space after source: %s", command_buf.buf);
2023 } else {
2024 endp = strchr(s, ' ');
2025 if (!endp)
2026 die("Missing space after source: %s", command_buf.buf);
2027 strbuf_add(&s_uq, s, endp - s);
2029 s = s_uq.buf;
2031 endp++;
2032 if (!*endp)
2033 die("Missing dest: %s", command_buf.buf);
2035 d = endp;
2036 strbuf_reset(&d_uq);
2037 if (!unquote_c_style(&d_uq, d, &endp)) {
2038 if (*endp)
2039 die("Garbage after dest in: %s", command_buf.buf);
2040 d = d_uq.buf;
2043 memset(&leaf, 0, sizeof(leaf));
2044 if (rename)
2045 tree_content_remove(&b->branch_tree, s, &leaf);
2046 else
2047 tree_content_get(&b->branch_tree, s, &leaf);
2048 if (!leaf.versions[1].mode)
2049 die("Path %s not in branch", s);
2050 tree_content_set(&b->branch_tree, d,
2051 leaf.versions[1].sha1,
2052 leaf.versions[1].mode,
2053 leaf.tree);
2056 static void file_change_deleteall(struct branch *b)
2058 release_tree_content_recursive(b->branch_tree.tree);
2059 hashclr(b->branch_tree.versions[0].sha1);
2060 hashclr(b->branch_tree.versions[1].sha1);
2061 load_tree(&b->branch_tree);
2064 static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2066 if (!buf || size < 46)
2067 die("Not a valid commit: %s", sha1_to_hex(b->sha1));
2068 if (memcmp("tree ", buf, 5)
2069 || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
2070 die("The commit %s is corrupt", sha1_to_hex(b->sha1));
2071 hashcpy(b->branch_tree.versions[0].sha1,
2072 b->branch_tree.versions[1].sha1);
2075 static void parse_from_existing(struct branch *b)
2077 if (is_null_sha1(b->sha1)) {
2078 hashclr(b->branch_tree.versions[0].sha1);
2079 hashclr(b->branch_tree.versions[1].sha1);
2080 } else {
2081 unsigned long size;
2082 char *buf;
2084 buf = read_object_with_reference(b->sha1,
2085 commit_type, &size, b->sha1);
2086 parse_from_commit(b, buf, size);
2087 free(buf);
2091 static int parse_from(struct branch *b)
2093 const char *from;
2094 struct branch *s;
2096 if (prefixcmp(command_buf.buf, "from "))
2097 return 0;
2099 if (b->branch_tree.tree) {
2100 release_tree_content_recursive(b->branch_tree.tree);
2101 b->branch_tree.tree = NULL;
2104 from = strchr(command_buf.buf, ' ') + 1;
2105 s = lookup_branch(from);
2106 if (b == s)
2107 die("Can't create a branch from itself: %s", b->name);
2108 else if (s) {
2109 unsigned char *t = s->branch_tree.versions[1].sha1;
2110 hashcpy(b->sha1, s->sha1);
2111 hashcpy(b->branch_tree.versions[0].sha1, t);
2112 hashcpy(b->branch_tree.versions[1].sha1, t);
2113 } else if (*from == ':') {
2114 uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2115 struct object_entry *oe = find_mark(idnum);
2116 if (oe->type != OBJ_COMMIT)
2117 die("Mark :%" PRIuMAX " not a commit", idnum);
2118 hashcpy(b->sha1, oe->sha1);
2119 if (oe->pack_id != MAX_PACK_ID) {
2120 unsigned long size;
2121 char *buf = gfi_unpack_entry(oe, &size);
2122 parse_from_commit(b, buf, size);
2123 free(buf);
2124 } else
2125 parse_from_existing(b);
2126 } else if (!get_sha1(from, b->sha1))
2127 parse_from_existing(b);
2128 else
2129 die("Invalid ref name or SHA1 expression: %s", from);
2131 read_next_command();
2132 return 1;
2135 static struct hash_list *parse_merge(unsigned int *count)
2137 struct hash_list *list = NULL, *n, *e = e;
2138 const char *from;
2139 struct branch *s;
2141 *count = 0;
2142 while (!prefixcmp(command_buf.buf, "merge ")) {
2143 from = strchr(command_buf.buf, ' ') + 1;
2144 n = xmalloc(sizeof(*n));
2145 s = lookup_branch(from);
2146 if (s)
2147 hashcpy(n->sha1, s->sha1);
2148 else if (*from == ':') {
2149 uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2150 struct object_entry *oe = find_mark(idnum);
2151 if (oe->type != OBJ_COMMIT)
2152 die("Mark :%" PRIuMAX " not a commit", idnum);
2153 hashcpy(n->sha1, oe->sha1);
2154 } else if (!get_sha1(from, n->sha1)) {
2155 unsigned long size;
2156 char *buf = read_object_with_reference(n->sha1,
2157 commit_type, &size, n->sha1);
2158 if (!buf || size < 46)
2159 die("Not a valid commit: %s", from);
2160 free(buf);
2161 } else
2162 die("Invalid ref name or SHA1 expression: %s", from);
2164 n->next = NULL;
2165 if (list)
2166 e->next = n;
2167 else
2168 list = n;
2169 e = n;
2170 (*count)++;
2171 read_next_command();
2173 return list;
2176 static void parse_new_commit(void)
2178 static struct strbuf msg = STRBUF_INIT;
2179 struct branch *b;
2180 char *sp;
2181 char *author = NULL;
2182 char *committer = NULL;
2183 struct hash_list *merge_list = NULL;
2184 unsigned int merge_count;
2186 /* Obtain the branch name from the rest of our command */
2187 sp = strchr(command_buf.buf, ' ') + 1;
2188 b = lookup_branch(sp);
2189 if (!b)
2190 b = new_branch(sp);
2192 read_next_command();
2193 parse_mark();
2194 if (!prefixcmp(command_buf.buf, "author ")) {
2195 author = parse_ident(command_buf.buf + 7);
2196 read_next_command();
2198 if (!prefixcmp(command_buf.buf, "committer ")) {
2199 committer = parse_ident(command_buf.buf + 10);
2200 read_next_command();
2202 if (!committer)
2203 die("Expected committer but didn't get one");
2204 parse_data(&msg);
2205 read_next_command();
2206 parse_from(b);
2207 merge_list = parse_merge(&merge_count);
2209 /* ensure the branch is active/loaded */
2210 if (!b->branch_tree.tree || !max_active_branches) {
2211 unload_one_branch();
2212 load_branch(b);
2215 /* file_change* */
2216 while (command_buf.len > 0) {
2217 if (!prefixcmp(command_buf.buf, "M "))
2218 file_change_m(b);
2219 else if (!prefixcmp(command_buf.buf, "D "))
2220 file_change_d(b);
2221 else if (!prefixcmp(command_buf.buf, "R "))
2222 file_change_cr(b, 1);
2223 else if (!prefixcmp(command_buf.buf, "C "))
2224 file_change_cr(b, 0);
2225 else if (!strcmp("deleteall", command_buf.buf))
2226 file_change_deleteall(b);
2227 else {
2228 unread_command_buf = 1;
2229 break;
2231 if (read_next_command() == EOF)
2232 break;
2235 /* build the tree and the commit */
2236 store_tree(&b->branch_tree);
2237 hashcpy(b->branch_tree.versions[0].sha1,
2238 b->branch_tree.versions[1].sha1);
2240 strbuf_reset(&new_data);
2241 strbuf_addf(&new_data, "tree %s\n",
2242 sha1_to_hex(b->branch_tree.versions[1].sha1));
2243 if (!is_null_sha1(b->sha1))
2244 strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(b->sha1));
2245 while (merge_list) {
2246 struct hash_list *next = merge_list->next;
2247 strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(merge_list->sha1));
2248 free(merge_list);
2249 merge_list = next;
2251 strbuf_addf(&new_data,
2252 "author %s\n"
2253 "committer %s\n"
2254 "\n",
2255 author ? author : committer, committer);
2256 strbuf_addbuf(&new_data, &msg);
2257 free(author);
2258 free(committer);
2260 if (!store_object(OBJ_COMMIT, &new_data, NULL, b->sha1, next_mark))
2261 b->pack_id = pack_id;
2262 b->last_commit = object_count_by_type[OBJ_COMMIT];
2265 static void parse_new_tag(void)
2267 static struct strbuf msg = STRBUF_INIT;
2268 char *sp;
2269 const char *from;
2270 char *tagger;
2271 struct branch *s;
2272 struct tag *t;
2273 uintmax_t from_mark = 0;
2274 unsigned char sha1[20];
2276 /* Obtain the new tag name from the rest of our command */
2277 sp = strchr(command_buf.buf, ' ') + 1;
2278 t = pool_alloc(sizeof(struct tag));
2279 t->next_tag = NULL;
2280 t->name = pool_strdup(sp);
2281 if (last_tag)
2282 last_tag->next_tag = t;
2283 else
2284 first_tag = t;
2285 last_tag = t;
2286 read_next_command();
2288 /* from ... */
2289 if (prefixcmp(command_buf.buf, "from "))
2290 die("Expected from command, got %s", command_buf.buf);
2291 from = strchr(command_buf.buf, ' ') + 1;
2292 s = lookup_branch(from);
2293 if (s) {
2294 hashcpy(sha1, s->sha1);
2295 } else if (*from == ':') {
2296 struct object_entry *oe;
2297 from_mark = strtoumax(from + 1, NULL, 10);
2298 oe = find_mark(from_mark);
2299 if (oe->type != OBJ_COMMIT)
2300 die("Mark :%" PRIuMAX " not a commit", from_mark);
2301 hashcpy(sha1, oe->sha1);
2302 } else if (!get_sha1(from, sha1)) {
2303 unsigned long size;
2304 char *buf;
2306 buf = read_object_with_reference(sha1,
2307 commit_type, &size, sha1);
2308 if (!buf || size < 46)
2309 die("Not a valid commit: %s", from);
2310 free(buf);
2311 } else
2312 die("Invalid ref name or SHA1 expression: %s", from);
2313 read_next_command();
2315 /* tagger ... */
2316 if (!prefixcmp(command_buf.buf, "tagger ")) {
2317 tagger = parse_ident(command_buf.buf + 7);
2318 read_next_command();
2319 } else
2320 tagger = NULL;
2322 /* tag payload/message */
2323 parse_data(&msg);
2325 /* build the tag object */
2326 strbuf_reset(&new_data);
2328 strbuf_addf(&new_data,
2329 "object %s\n"
2330 "type %s\n"
2331 "tag %s\n",
2332 sha1_to_hex(sha1), commit_type, t->name);
2333 if (tagger)
2334 strbuf_addf(&new_data,
2335 "tagger %s\n", tagger);
2336 strbuf_addch(&new_data, '\n');
2337 strbuf_addbuf(&new_data, &msg);
2338 free(tagger);
2340 if (store_object(OBJ_TAG, &new_data, NULL, t->sha1, 0))
2341 t->pack_id = MAX_PACK_ID;
2342 else
2343 t->pack_id = pack_id;
2346 static void parse_reset_branch(void)
2348 struct branch *b;
2349 char *sp;
2351 /* Obtain the branch name from the rest of our command */
2352 sp = strchr(command_buf.buf, ' ') + 1;
2353 b = lookup_branch(sp);
2354 if (b) {
2355 hashclr(b->sha1);
2356 hashclr(b->branch_tree.versions[0].sha1);
2357 hashclr(b->branch_tree.versions[1].sha1);
2358 if (b->branch_tree.tree) {
2359 release_tree_content_recursive(b->branch_tree.tree);
2360 b->branch_tree.tree = NULL;
2363 else
2364 b = new_branch(sp);
2365 read_next_command();
2366 parse_from(b);
2367 if (command_buf.len > 0)
2368 unread_command_buf = 1;
2371 static void parse_checkpoint(void)
2373 if (object_count) {
2374 cycle_packfile();
2375 dump_branches();
2376 dump_tags();
2377 dump_marks();
2379 skip_optional_lf();
2382 static void parse_progress(void)
2384 fwrite(command_buf.buf, 1, command_buf.len, stdout);
2385 fputc('\n', stdout);
2386 fflush(stdout);
2387 skip_optional_lf();
2390 static void option_import_marks(const char *marks)
2392 input_file = xstrdup(marks);
2395 static void option_date_format(const char *fmt)
2397 if (!strcmp(fmt, "raw"))
2398 whenspec = WHENSPEC_RAW;
2399 else if (!strcmp(fmt, "rfc2822"))
2400 whenspec = WHENSPEC_RFC2822;
2401 else if (!strcmp(fmt, "now"))
2402 whenspec = WHENSPEC_NOW;
2403 else
2404 die("unknown --date-format argument %s", fmt);
2407 static void option_max_pack_size(const char *packsize)
2409 max_packsize = strtoumax(packsize, NULL, 0) * 1024 * 1024;
2412 static void option_depth(const char *depth)
2414 max_depth = strtoul(depth, NULL, 0);
2415 if (max_depth > MAX_DEPTH)
2416 die("--depth cannot exceed %u", MAX_DEPTH);
2419 static void option_active_branches(const char *branches)
2421 max_active_branches = strtoul(branches, NULL, 0);
2424 static void option_export_marks(const char *marks)
2426 mark_file = xstrdup(marks);
2429 static void option_export_pack_edges(const char *edges)
2431 if (pack_edges)
2432 fclose(pack_edges);
2433 pack_edges = fopen(edges, "a");
2434 if (!pack_edges)
2435 die_errno("Cannot open '%s'", edges);
2438 static void parse_one_option(const char *option, int optional)
2440 if (!prefixcmp(option, "date-format=")) {
2441 option_date_format(option + 12);
2442 } else if (!prefixcmp(option, "max-pack-size=")) {
2443 option_max_pack_size(option + 14);
2444 } else if (!prefixcmp(option, "depth=")) {
2445 option_depth(option + 6);
2446 } else if (!prefixcmp(option, "active-branches=")) {
2447 option_active_branches(option + 16);
2448 } else if (!prefixcmp(option, "import-marks=")) {
2449 option_import_marks(option + 13);
2450 } else if (!prefixcmp(option, "export-marks=")) {
2451 option_export_marks(option + 13);
2452 } else if (!prefixcmp(option, "export-pack-edges=")) {
2453 option_export_pack_edges(option + 18);
2454 } else if (!prefixcmp(option, "force")) {
2455 force_update = 1;
2456 } else if (!prefixcmp(option, "quiet")) {
2457 show_stats = 0;
2458 } else if (!prefixcmp(option, "stats")) {
2459 show_stats = 1;
2460 } else if (!optional) {
2461 die("Unsupported option: %s", option);
2465 static void parse_feature(void)
2467 char *feature = command_buf.buf + 8;
2469 if (!prefixcmp(feature, "date-format=")) {
2470 option_date_format(feature + 12);
2471 } else if (!strcmp("git-options", feature)) {
2472 options_enabled = 1;
2473 } else {
2474 die("This version of fast-import does not support feature %s.", feature);
2478 static void parse_option(void)
2480 char *option = command_buf.buf + 11;
2482 if (!options_enabled)
2483 die("Got option command '%s' before options feature'", option);
2485 if (seen_non_option_command)
2486 die("Got option command '%s' after non-option command", option);
2488 /* ignore unknown options, instead of erroring */
2489 parse_one_option(option, 1);
2492 static void parse_nongit_option(void)
2494 /* do nothing */
2497 static int git_pack_config(const char *k, const char *v, void *cb)
2499 if (!strcmp(k, "pack.depth")) {
2500 max_depth = git_config_int(k, v);
2501 if (max_depth > MAX_DEPTH)
2502 max_depth = MAX_DEPTH;
2503 return 0;
2505 if (!strcmp(k, "pack.compression")) {
2506 int level = git_config_int(k, v);
2507 if (level == -1)
2508 level = Z_DEFAULT_COMPRESSION;
2509 else if (level < 0 || level > Z_BEST_COMPRESSION)
2510 die("bad pack compression level %d", level);
2511 pack_compression_level = level;
2512 pack_compression_seen = 1;
2513 return 0;
2515 return git_default_config(k, v, cb);
2518 static const char fast_import_usage[] =
2519 "git fast-import [--date-format=f] [--max-pack-size=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file]";
2521 static void parse_argv(void)
2523 unsigned int i;
2525 for (i = 1; i < global_argc; i++) {
2526 const char *a = global_argv[i];
2528 if (*a != '-' || !strcmp(a, "--"))
2529 break;
2531 /* error on unknown options */
2532 parse_one_option(a + 2, 0);
2534 if (i != global_argc)
2535 usage(fast_import_usage);
2537 seen_non_option_command = 1;
2538 if (input_file)
2539 read_marks();
2542 int main(int argc, const char **argv)
2544 unsigned int i;
2546 git_extract_argv0_path(argv[0]);
2548 setup_git_directory();
2549 git_config(git_pack_config, NULL);
2550 if (!pack_compression_seen && core_compression_seen)
2551 pack_compression_level = core_compression_level;
2553 alloc_objects(object_entry_alloc);
2554 strbuf_init(&command_buf, 0);
2555 atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
2556 branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
2557 avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
2558 marks = pool_calloc(1, sizeof(struct mark_set));
2560 global_argc = argc;
2561 global_argv = argv;
2563 rc_free = pool_alloc(cmd_save * sizeof(*rc_free));
2564 for (i = 0; i < (cmd_save - 1); i++)
2565 rc_free[i].next = &rc_free[i + 1];
2566 rc_free[cmd_save - 1].next = NULL;
2568 prepare_packed_git();
2569 start_packfile();
2570 set_die_routine(die_nicely);
2571 while (read_next_command() != EOF) {
2572 if (!strcmp("blob", command_buf.buf))
2573 parse_new_blob();
2574 else if (!prefixcmp(command_buf.buf, "commit "))
2575 parse_new_commit();
2576 else if (!prefixcmp(command_buf.buf, "tag "))
2577 parse_new_tag();
2578 else if (!prefixcmp(command_buf.buf, "reset "))
2579 parse_reset_branch();
2580 else if (!strcmp("checkpoint", command_buf.buf))
2581 parse_checkpoint();
2582 else if (!prefixcmp(command_buf.buf, "progress "))
2583 parse_progress();
2584 else if (!prefixcmp(command_buf.buf, "feature "))
2585 parse_feature();
2586 else if (!prefixcmp(command_buf.buf, "option git "))
2587 parse_option();
2588 else if (!prefixcmp(command_buf.buf, "option "))
2589 parse_nongit_option();
2590 else
2591 die("Unsupported command: %s", command_buf.buf);
2594 /* argv hasn't been parsed yet, do so */
2595 if (!seen_non_option_command)
2596 parse_argv();
2598 end_packfile();
2600 dump_branches();
2601 dump_tags();
2602 unkeep_all_packs();
2603 dump_marks();
2605 if (pack_edges)
2606 fclose(pack_edges);
2608 if (show_stats) {
2609 uintmax_t total_count = 0, duplicate_count = 0;
2610 for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
2611 total_count += object_count_by_type[i];
2612 for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
2613 duplicate_count += duplicate_count_by_type[i];
2615 fprintf(stderr, "%s statistics:\n", argv[0]);
2616 fprintf(stderr, "---------------------------------------------------------------------\n");
2617 fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
2618 fprintf(stderr, "Total objects: %10" PRIuMAX " (%10" PRIuMAX " duplicates )\n", total_count, duplicate_count);
2619 fprintf(stderr, " blobs : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB]);
2620 fprintf(stderr, " trees : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE]);
2621 fprintf(stderr, " commits: %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT]);
2622 fprintf(stderr, " tags : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG]);
2623 fprintf(stderr, "Total branches: %10lu (%10lu loads )\n", branch_count, branch_load_count);
2624 fprintf(stderr, " marks: %10" PRIuMAX " (%10" PRIuMAX " unique )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
2625 fprintf(stderr, " atoms: %10u\n", atom_cnt);
2626 fprintf(stderr, "Memory total: %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
2627 fprintf(stderr, " pools: %10lu KiB\n", (unsigned long)(total_allocd/1024));
2628 fprintf(stderr, " objects: %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
2629 fprintf(stderr, "---------------------------------------------------------------------\n");
2630 pack_report();
2631 fprintf(stderr, "---------------------------------------------------------------------\n");
2632 fprintf(stderr, "\n");
2635 return failure ? 1 : 0;