mem-pool: move reusable parts of memory pool into its own file
[git.git] / fast-import.c
blobba0cb4bdfb69c3127058a3b923c94f1ea613508b
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 commit-ish lf)?
26 ('merge' sp commit-ish lf)*
27 (file_change | ls)*
28 lf?;
29 commit_msg ::= data;
31 ls ::= 'ls' sp '"' quoted(path) '"' lf;
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;
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;
56 reset_branch ::= 'reset' sp ref_str lf
57 ('from' sp commit-ish lf)?
58 lf?;
60 checkpoint ::= 'checkpoint' lf
61 lf?;
63 progress ::= 'progress' sp not_lf* lf
64 lf?;
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.
72 mark ::= 'mark' sp idnum lf;
73 data ::= (delimited_data | exact_data)
74 lf?;
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;
83 # note: declen indicates the length of binary_data in bytes.
84 # declen does not include the lf preceding the binary data.
86 exact_data ::= 'data' sp declen lf
87 binary_data;
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.
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'
106 declen ::= # unsigned 32 bit value, ascii base10 notation;
107 bigint ::= # unsigned integer value, ascii base10 notation;
108 binary_data ::= # file content, not interpreted;
110 when ::= raw_when | rfc2822_when;
111 raw_when ::= ts sp tz;
112 rfc2822_when ::= # Valid RFC 2822 date and time;
114 sp ::= # ASCII space character;
115 lf ::= # ASCII newline (LF) character;
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.
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;
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.
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;
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.
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).
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;
151 comment ::= '#' not_lf* lf;
152 not_lf ::= # Any byte that is not ASCII newline (LF);
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 #include "mem-pool.h"
173 #define PACK_ID_BITS 16
174 #define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
175 #define DEPTH_BITS 13
176 #define MAX_DEPTH ((1<<DEPTH_BITS)-1)
179 * We abuse the setuid bit on directories to mean "do not delta".
181 #define NO_DELTA S_ISUID
183 struct object_entry {
184 struct pack_idx_entry idx;
185 struct object_entry *next;
186 uint32_t type : TYPE_BITS,
187 pack_id : PACK_ID_BITS,
188 depth : DEPTH_BITS;
191 struct object_entry_pool {
192 struct object_entry_pool *next_pool;
193 struct object_entry *next_free;
194 struct object_entry *end;
195 struct object_entry entries[FLEX_ARRAY]; /* more */
198 struct mark_set {
199 union {
200 struct object_entry *marked[1024];
201 struct mark_set *sets[1024];
202 } data;
203 unsigned int shift;
206 struct last_object {
207 struct strbuf data;
208 off_t offset;
209 unsigned int depth;
210 unsigned no_swap : 1;
213 struct atom_str {
214 struct atom_str *next_atom;
215 unsigned short str_len;
216 char str_dat[FLEX_ARRAY]; /* more */
219 struct tree_content;
220 struct tree_entry {
221 struct tree_content *tree;
222 struct atom_str *name;
223 struct tree_entry_ms {
224 uint16_t mode;
225 struct object_id oid;
226 } versions[2];
229 struct tree_content {
230 unsigned int entry_capacity; /* must match avail_tree_content */
231 unsigned int entry_count;
232 unsigned int delta_depth;
233 struct tree_entry *entries[FLEX_ARRAY]; /* more */
236 struct avail_tree_content {
237 unsigned int entry_capacity; /* must match tree_content */
238 struct avail_tree_content *next_avail;
241 struct branch {
242 struct branch *table_next_branch;
243 struct branch *active_next_branch;
244 const char *name;
245 struct tree_entry branch_tree;
246 uintmax_t last_commit;
247 uintmax_t num_notes;
248 unsigned active : 1;
249 unsigned delete : 1;
250 unsigned pack_id : PACK_ID_BITS;
251 struct object_id oid;
254 struct tag {
255 struct tag *next_tag;
256 const char *name;
257 unsigned int pack_id;
258 struct object_id oid;
261 struct hash_list {
262 struct hash_list *next;
263 struct object_id oid;
266 typedef enum {
267 WHENSPEC_RAW = 1,
268 WHENSPEC_RFC2822,
269 WHENSPEC_NOW
270 } whenspec_type;
272 struct recent_command {
273 struct recent_command *prev;
274 struct recent_command *next;
275 char *buf;
278 /* Configured limits on output */
279 static unsigned long max_depth = 50;
280 static off_t max_packsize;
281 static int unpack_limit = 100;
282 static int force_update;
284 /* Stats and misc. counters */
285 static uintmax_t alloc_count;
286 static uintmax_t marks_set_count;
287 static uintmax_t object_count_by_type[1 << TYPE_BITS];
288 static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
289 static uintmax_t delta_count_by_type[1 << TYPE_BITS];
290 static uintmax_t delta_count_attempts_by_type[1 << TYPE_BITS];
291 static unsigned long object_count;
292 static unsigned long branch_count;
293 static unsigned long branch_load_count;
294 static int failure;
295 static FILE *pack_edges;
296 static unsigned int show_stats = 1;
297 static int global_argc;
298 static const char **global_argv;
300 /* Memory pools */
301 static struct mem_pool fi_mem_pool = {NULL, 2*1024*1024 -
302 sizeof(struct mp_block), 0 };
304 /* Atom management */
305 static unsigned int atom_table_sz = 4451;
306 static unsigned int atom_cnt;
307 static struct atom_str **atom_table;
309 /* The .pack file being generated */
310 static struct pack_idx_option pack_idx_opts;
311 static unsigned int pack_id;
312 static struct hashfile *pack_file;
313 static struct packed_git *pack_data;
314 static struct packed_git **all_packs;
315 static off_t pack_size;
317 /* Table of objects we've written. */
318 static unsigned int object_entry_alloc = 5000;
319 static struct object_entry_pool *blocks;
320 static struct object_entry *object_table[1 << 16];
321 static struct mark_set *marks;
322 static const char *export_marks_file;
323 static const char *import_marks_file;
324 static int import_marks_file_from_stream;
325 static int import_marks_file_ignore_missing;
326 static int import_marks_file_done;
327 static int relative_marks_paths;
329 /* Our last blob */
330 static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
332 /* Tree management */
333 static unsigned int tree_entry_alloc = 1000;
334 static void *avail_tree_entry;
335 static unsigned int avail_tree_table_sz = 100;
336 static struct avail_tree_content **avail_tree_table;
337 static size_t tree_entry_allocd;
338 static struct strbuf old_tree = STRBUF_INIT;
339 static struct strbuf new_tree = STRBUF_INIT;
341 /* Branch data */
342 static unsigned long max_active_branches = 5;
343 static unsigned long cur_active_branches;
344 static unsigned long branch_table_sz = 1039;
345 static struct branch **branch_table;
346 static struct branch *active_branches;
348 /* Tag data */
349 static struct tag *first_tag;
350 static struct tag *last_tag;
352 /* Input stream parsing */
353 static whenspec_type whenspec = WHENSPEC_RAW;
354 static struct strbuf command_buf = STRBUF_INIT;
355 static int unread_command_buf;
356 static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
357 static struct recent_command *cmd_tail = &cmd_hist;
358 static struct recent_command *rc_free;
359 static unsigned int cmd_save = 100;
360 static uintmax_t next_mark;
361 static struct strbuf new_data = STRBUF_INIT;
362 static int seen_data_command;
363 static int require_explicit_termination;
365 /* Signal handling */
366 static volatile sig_atomic_t checkpoint_requested;
368 /* Where to write output of cat-blob commands */
369 static int cat_blob_fd = STDOUT_FILENO;
371 static void parse_argv(void);
372 static void parse_get_mark(const char *p);
373 static void parse_cat_blob(const char *p);
374 static void parse_ls(const char *p, struct branch *b);
376 static void write_branch_report(FILE *rpt, struct branch *b)
378 fprintf(rpt, "%s:\n", b->name);
380 fprintf(rpt, " status :");
381 if (b->active)
382 fputs(" active", rpt);
383 if (b->branch_tree.tree)
384 fputs(" loaded", rpt);
385 if (is_null_oid(&b->branch_tree.versions[1].oid))
386 fputs(" dirty", rpt);
387 fputc('\n', rpt);
389 fprintf(rpt, " tip commit : %s\n", oid_to_hex(&b->oid));
390 fprintf(rpt, " old tree : %s\n",
391 oid_to_hex(&b->branch_tree.versions[0].oid));
392 fprintf(rpt, " cur tree : %s\n",
393 oid_to_hex(&b->branch_tree.versions[1].oid));
394 fprintf(rpt, " commit clock: %" PRIuMAX "\n", b->last_commit);
396 fputs(" last pack : ", rpt);
397 if (b->pack_id < MAX_PACK_ID)
398 fprintf(rpt, "%u", b->pack_id);
399 fputc('\n', rpt);
401 fputc('\n', rpt);
404 static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *);
406 static void write_crash_report(const char *err)
408 char *loc = git_pathdup("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
409 FILE *rpt = fopen(loc, "w");
410 struct branch *b;
411 unsigned long lu;
412 struct recent_command *rc;
414 if (!rpt) {
415 error_errno("can't write crash report %s", loc);
416 free(loc);
417 return;
420 fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
422 fprintf(rpt, "fast-import crash report:\n");
423 fprintf(rpt, " fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
424 fprintf(rpt, " parent process : %"PRIuMAX"\n", (uintmax_t) getppid());
425 fprintf(rpt, " at %s\n", show_date(time(NULL), 0, DATE_MODE(ISO8601)));
426 fputc('\n', rpt);
428 fputs("fatal: ", rpt);
429 fputs(err, rpt);
430 fputc('\n', rpt);
432 fputc('\n', rpt);
433 fputs("Most Recent Commands Before Crash\n", rpt);
434 fputs("---------------------------------\n", rpt);
435 for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
436 if (rc->next == &cmd_hist)
437 fputs("* ", rpt);
438 else
439 fputs(" ", rpt);
440 fputs(rc->buf, rpt);
441 fputc('\n', rpt);
444 fputc('\n', rpt);
445 fputs("Active Branch LRU\n", rpt);
446 fputs("-----------------\n", rpt);
447 fprintf(rpt, " active_branches = %lu cur, %lu max\n",
448 cur_active_branches,
449 max_active_branches);
450 fputc('\n', rpt);
451 fputs(" pos clock name\n", rpt);
452 fputs(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
453 for (b = active_branches, lu = 0; b; b = b->active_next_branch)
454 fprintf(rpt, " %2lu) %6" PRIuMAX" %s\n",
455 ++lu, b->last_commit, b->name);
457 fputc('\n', rpt);
458 fputs("Inactive Branches\n", rpt);
459 fputs("-----------------\n", rpt);
460 for (lu = 0; lu < branch_table_sz; lu++) {
461 for (b = branch_table[lu]; b; b = b->table_next_branch)
462 write_branch_report(rpt, b);
465 if (first_tag) {
466 struct tag *tg;
467 fputc('\n', rpt);
468 fputs("Annotated Tags\n", rpt);
469 fputs("--------------\n", rpt);
470 for (tg = first_tag; tg; tg = tg->next_tag) {
471 fputs(oid_to_hex(&tg->oid), rpt);
472 fputc(' ', rpt);
473 fputs(tg->name, rpt);
474 fputc('\n', rpt);
478 fputc('\n', rpt);
479 fputs("Marks\n", rpt);
480 fputs("-----\n", rpt);
481 if (export_marks_file)
482 fprintf(rpt, " exported to %s\n", export_marks_file);
483 else
484 dump_marks_helper(rpt, 0, marks);
486 fputc('\n', rpt);
487 fputs("-------------------\n", rpt);
488 fputs("END OF CRASH REPORT\n", rpt);
489 fclose(rpt);
490 free(loc);
493 static void end_packfile(void);
494 static void unkeep_all_packs(void);
495 static void dump_marks(void);
497 static NORETURN void die_nicely(const char *err, va_list params)
499 static int zombie;
500 char message[2 * PATH_MAX];
502 vsnprintf(message, sizeof(message), err, params);
503 fputs("fatal: ", stderr);
504 fputs(message, stderr);
505 fputc('\n', stderr);
507 if (!zombie) {
508 zombie = 1;
509 write_crash_report(message);
510 end_packfile();
511 unkeep_all_packs();
512 dump_marks();
514 exit(128);
517 #ifndef SIGUSR1 /* Windows, for example */
519 static void set_checkpoint_signal(void)
523 #else
525 static void checkpoint_signal(int signo)
527 checkpoint_requested = 1;
530 static void set_checkpoint_signal(void)
532 struct sigaction sa;
534 memset(&sa, 0, sizeof(sa));
535 sa.sa_handler = checkpoint_signal;
536 sigemptyset(&sa.sa_mask);
537 sa.sa_flags = SA_RESTART;
538 sigaction(SIGUSR1, &sa, NULL);
541 #endif
543 static void alloc_objects(unsigned int cnt)
545 struct object_entry_pool *b;
547 b = xmalloc(sizeof(struct object_entry_pool)
548 + cnt * sizeof(struct object_entry));
549 b->next_pool = blocks;
550 b->next_free = b->entries;
551 b->end = b->entries + cnt;
552 blocks = b;
553 alloc_count += cnt;
556 static struct object_entry *new_object(struct object_id *oid)
558 struct object_entry *e;
560 if (blocks->next_free == blocks->end)
561 alloc_objects(object_entry_alloc);
563 e = blocks->next_free++;
564 oidcpy(&e->idx.oid, oid);
565 return e;
568 static struct object_entry *find_object(struct object_id *oid)
570 unsigned int h = oid->hash[0] << 8 | oid->hash[1];
571 struct object_entry *e;
572 for (e = object_table[h]; e; e = e->next)
573 if (!oidcmp(oid, &e->idx.oid))
574 return e;
575 return NULL;
578 static struct object_entry *insert_object(struct object_id *oid)
580 unsigned int h = oid->hash[0] << 8 | oid->hash[1];
581 struct object_entry *e = object_table[h];
583 while (e) {
584 if (!oidcmp(oid, &e->idx.oid))
585 return e;
586 e = e->next;
589 e = new_object(oid);
590 e->next = object_table[h];
591 e->idx.offset = 0;
592 object_table[h] = e;
593 return e;
596 static void invalidate_pack_id(unsigned int id)
598 unsigned int h;
599 unsigned long lu;
600 struct tag *t;
602 for (h = 0; h < ARRAY_SIZE(object_table); h++) {
603 struct object_entry *e;
605 for (e = object_table[h]; e; e = e->next)
606 if (e->pack_id == id)
607 e->pack_id = MAX_PACK_ID;
610 for (lu = 0; lu < branch_table_sz; lu++) {
611 struct branch *b;
613 for (b = branch_table[lu]; b; b = b->table_next_branch)
614 if (b->pack_id == id)
615 b->pack_id = MAX_PACK_ID;
618 for (t = first_tag; t; t = t->next_tag)
619 if (t->pack_id == id)
620 t->pack_id = MAX_PACK_ID;
623 static unsigned int hc_str(const char *s, size_t len)
625 unsigned int r = 0;
626 while (len-- > 0)
627 r = r * 31 + *s++;
628 return r;
631 static char *pool_strdup(const char *s)
633 size_t len = strlen(s) + 1;
634 char *r = mem_pool_alloc(&fi_mem_pool, len);
635 memcpy(r, s, len);
636 return r;
639 static void insert_mark(uintmax_t idnum, struct object_entry *oe)
641 struct mark_set *s = marks;
642 while ((idnum >> s->shift) >= 1024) {
643 s = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
644 s->shift = marks->shift + 10;
645 s->data.sets[0] = marks;
646 marks = s;
648 while (s->shift) {
649 uintmax_t i = idnum >> s->shift;
650 idnum -= i << s->shift;
651 if (!s->data.sets[i]) {
652 s->data.sets[i] = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
653 s->data.sets[i]->shift = s->shift - 10;
655 s = s->data.sets[i];
657 if (!s->data.marked[idnum])
658 marks_set_count++;
659 s->data.marked[idnum] = oe;
662 static struct object_entry *find_mark(uintmax_t idnum)
664 uintmax_t orig_idnum = idnum;
665 struct mark_set *s = marks;
666 struct object_entry *oe = NULL;
667 if ((idnum >> s->shift) < 1024) {
668 while (s && s->shift) {
669 uintmax_t i = idnum >> s->shift;
670 idnum -= i << s->shift;
671 s = s->data.sets[i];
673 if (s)
674 oe = s->data.marked[idnum];
676 if (!oe)
677 die("mark :%" PRIuMAX " not declared", orig_idnum);
678 return oe;
681 static struct atom_str *to_atom(const char *s, unsigned short len)
683 unsigned int hc = hc_str(s, len) % atom_table_sz;
684 struct atom_str *c;
686 for (c = atom_table[hc]; c; c = c->next_atom)
687 if (c->str_len == len && !strncmp(s, c->str_dat, len))
688 return c;
690 c = mem_pool_alloc(&fi_mem_pool, sizeof(struct atom_str) + len + 1);
691 c->str_len = len;
692 memcpy(c->str_dat, s, len);
693 c->str_dat[len] = 0;
694 c->next_atom = atom_table[hc];
695 atom_table[hc] = c;
696 atom_cnt++;
697 return c;
700 static struct branch *lookup_branch(const char *name)
702 unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
703 struct branch *b;
705 for (b = branch_table[hc]; b; b = b->table_next_branch)
706 if (!strcmp(name, b->name))
707 return b;
708 return NULL;
711 static struct branch *new_branch(const char *name)
713 unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
714 struct branch *b = lookup_branch(name);
716 if (b)
717 die("Invalid attempt to create duplicate branch: %s", name);
718 if (check_refname_format(name, REFNAME_ALLOW_ONELEVEL))
719 die("Branch name doesn't conform to GIT standards: %s", name);
721 b = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct branch));
722 b->name = pool_strdup(name);
723 b->table_next_branch = branch_table[hc];
724 b->branch_tree.versions[0].mode = S_IFDIR;
725 b->branch_tree.versions[1].mode = S_IFDIR;
726 b->num_notes = 0;
727 b->active = 0;
728 b->pack_id = MAX_PACK_ID;
729 branch_table[hc] = b;
730 branch_count++;
731 return b;
734 static unsigned int hc_entries(unsigned int cnt)
736 cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
737 return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
740 static struct tree_content *new_tree_content(unsigned int cnt)
742 struct avail_tree_content *f, *l = NULL;
743 struct tree_content *t;
744 unsigned int hc = hc_entries(cnt);
746 for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
747 if (f->entry_capacity >= cnt)
748 break;
750 if (f) {
751 if (l)
752 l->next_avail = f->next_avail;
753 else
754 avail_tree_table[hc] = f->next_avail;
755 } else {
756 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
757 f = mem_pool_alloc(&fi_mem_pool, sizeof(*t) + sizeof(t->entries[0]) * cnt);
758 f->entry_capacity = cnt;
761 t = (struct tree_content*)f;
762 t->entry_count = 0;
763 t->delta_depth = 0;
764 return t;
767 static void release_tree_entry(struct tree_entry *e);
768 static void release_tree_content(struct tree_content *t)
770 struct avail_tree_content *f = (struct avail_tree_content*)t;
771 unsigned int hc = hc_entries(f->entry_capacity);
772 f->next_avail = avail_tree_table[hc];
773 avail_tree_table[hc] = f;
776 static void release_tree_content_recursive(struct tree_content *t)
778 unsigned int i;
779 for (i = 0; i < t->entry_count; i++)
780 release_tree_entry(t->entries[i]);
781 release_tree_content(t);
784 static struct tree_content *grow_tree_content(
785 struct tree_content *t,
786 int amt)
788 struct tree_content *r = new_tree_content(t->entry_count + amt);
789 r->entry_count = t->entry_count;
790 r->delta_depth = t->delta_depth;
791 memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
792 release_tree_content(t);
793 return r;
796 static struct tree_entry *new_tree_entry(void)
798 struct tree_entry *e;
800 if (!avail_tree_entry) {
801 unsigned int n = tree_entry_alloc;
802 tree_entry_allocd += n * sizeof(struct tree_entry);
803 ALLOC_ARRAY(e, n);
804 avail_tree_entry = e;
805 while (n-- > 1) {
806 *((void**)e) = e + 1;
807 e++;
809 *((void**)e) = NULL;
812 e = avail_tree_entry;
813 avail_tree_entry = *((void**)e);
814 return e;
817 static void release_tree_entry(struct tree_entry *e)
819 if (e->tree)
820 release_tree_content_recursive(e->tree);
821 *((void**)e) = avail_tree_entry;
822 avail_tree_entry = e;
825 static struct tree_content *dup_tree_content(struct tree_content *s)
827 struct tree_content *d;
828 struct tree_entry *a, *b;
829 unsigned int i;
831 if (!s)
832 return NULL;
833 d = new_tree_content(s->entry_count);
834 for (i = 0; i < s->entry_count; i++) {
835 a = s->entries[i];
836 b = new_tree_entry();
837 memcpy(b, a, sizeof(*a));
838 if (a->tree && is_null_oid(&b->versions[1].oid))
839 b->tree = dup_tree_content(a->tree);
840 else
841 b->tree = NULL;
842 d->entries[i] = b;
844 d->entry_count = s->entry_count;
845 d->delta_depth = s->delta_depth;
847 return d;
850 static void start_packfile(void)
852 struct strbuf tmp_file = STRBUF_INIT;
853 struct packed_git *p;
854 struct pack_header hdr;
855 int pack_fd;
857 pack_fd = odb_mkstemp(&tmp_file, "pack/tmp_pack_XXXXXX");
858 FLEX_ALLOC_STR(p, pack_name, tmp_file.buf);
859 strbuf_release(&tmp_file);
861 p->pack_fd = pack_fd;
862 p->do_not_close = 1;
863 pack_file = hashfd(pack_fd, p->pack_name);
865 hdr.hdr_signature = htonl(PACK_SIGNATURE);
866 hdr.hdr_version = htonl(2);
867 hdr.hdr_entries = 0;
868 hashwrite(pack_file, &hdr, sizeof(hdr));
870 pack_data = p;
871 pack_size = sizeof(hdr);
872 object_count = 0;
874 REALLOC_ARRAY(all_packs, pack_id + 1);
875 all_packs[pack_id] = p;
878 static const char *create_index(void)
880 const char *tmpfile;
881 struct pack_idx_entry **idx, **c, **last;
882 struct object_entry *e;
883 struct object_entry_pool *o;
885 /* Build the table of object IDs. */
886 ALLOC_ARRAY(idx, object_count);
887 c = idx;
888 for (o = blocks; o; o = o->next_pool)
889 for (e = o->next_free; e-- != o->entries;)
890 if (pack_id == e->pack_id)
891 *c++ = &e->idx;
892 last = idx + object_count;
893 if (c != last)
894 die("internal consistency error creating the index");
896 tmpfile = write_idx_file(NULL, idx, object_count, &pack_idx_opts, pack_data->sha1);
897 free(idx);
898 return tmpfile;
901 static char *keep_pack(const char *curr_index_name)
903 static const char *keep_msg = "fast-import";
904 struct strbuf name = STRBUF_INIT;
905 int keep_fd;
907 odb_pack_name(&name, pack_data->sha1, "keep");
908 keep_fd = odb_pack_keep(name.buf);
909 if (keep_fd < 0)
910 die_errno("cannot create keep file");
911 write_or_die(keep_fd, keep_msg, strlen(keep_msg));
912 if (close(keep_fd))
913 die_errno("failed to write keep file");
915 odb_pack_name(&name, pack_data->sha1, "pack");
916 if (finalize_object_file(pack_data->pack_name, name.buf))
917 die("cannot store pack file");
919 odb_pack_name(&name, pack_data->sha1, "idx");
920 if (finalize_object_file(curr_index_name, name.buf))
921 die("cannot store index file");
922 free((void *)curr_index_name);
923 return strbuf_detach(&name, NULL);
926 static void unkeep_all_packs(void)
928 struct strbuf name = STRBUF_INIT;
929 int k;
931 for (k = 0; k < pack_id; k++) {
932 struct packed_git *p = all_packs[k];
933 odb_pack_name(&name, p->sha1, "keep");
934 unlink_or_warn(name.buf);
936 strbuf_release(&name);
939 static int loosen_small_pack(const struct packed_git *p)
941 struct child_process unpack = CHILD_PROCESS_INIT;
943 if (lseek(p->pack_fd, 0, SEEK_SET) < 0)
944 die_errno("Failed seeking to start of '%s'", p->pack_name);
946 unpack.in = p->pack_fd;
947 unpack.git_cmd = 1;
948 unpack.stdout_to_stderr = 1;
949 argv_array_push(&unpack.args, "unpack-objects");
950 if (!show_stats)
951 argv_array_push(&unpack.args, "-q");
953 return run_command(&unpack);
956 static void end_packfile(void)
958 static int running;
960 if (running || !pack_data)
961 return;
963 running = 1;
964 clear_delta_base_cache();
965 if (object_count) {
966 struct packed_git *new_p;
967 struct object_id cur_pack_oid;
968 char *idx_name;
969 int i;
970 struct branch *b;
971 struct tag *t;
973 close_pack_windows(pack_data);
974 hashclose(pack_file, cur_pack_oid.hash, 0);
975 fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
976 pack_data->pack_name, object_count,
977 cur_pack_oid.hash, pack_size);
979 if (object_count <= unpack_limit) {
980 if (!loosen_small_pack(pack_data)) {
981 invalidate_pack_id(pack_id);
982 goto discard_pack;
986 close(pack_data->pack_fd);
987 idx_name = keep_pack(create_index());
989 /* Register the packfile with core git's machinery. */
990 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
991 if (!new_p)
992 die("core git rejected index %s", idx_name);
993 all_packs[pack_id] = new_p;
994 install_packed_git(new_p);
995 free(idx_name);
997 /* Print the boundary */
998 if (pack_edges) {
999 fprintf(pack_edges, "%s:", new_p->pack_name);
1000 for (i = 0; i < branch_table_sz; i++) {
1001 for (b = branch_table[i]; b; b = b->table_next_branch) {
1002 if (b->pack_id == pack_id)
1003 fprintf(pack_edges, " %s",
1004 oid_to_hex(&b->oid));
1007 for (t = first_tag; t; t = t->next_tag) {
1008 if (t->pack_id == pack_id)
1009 fprintf(pack_edges, " %s",
1010 oid_to_hex(&t->oid));
1012 fputc('\n', pack_edges);
1013 fflush(pack_edges);
1016 pack_id++;
1018 else {
1019 discard_pack:
1020 close(pack_data->pack_fd);
1021 unlink_or_warn(pack_data->pack_name);
1023 FREE_AND_NULL(pack_data);
1024 running = 0;
1026 /* We can't carry a delta across packfiles. */
1027 strbuf_release(&last_blob.data);
1028 last_blob.offset = 0;
1029 last_blob.depth = 0;
1032 static void cycle_packfile(void)
1034 end_packfile();
1035 start_packfile();
1038 static int store_object(
1039 enum object_type type,
1040 struct strbuf *dat,
1041 struct last_object *last,
1042 struct object_id *oidout,
1043 uintmax_t mark)
1045 void *out, *delta;
1046 struct object_entry *e;
1047 unsigned char hdr[96];
1048 struct object_id oid;
1049 unsigned long hdrlen, deltalen;
1050 git_hash_ctx c;
1051 git_zstream s;
1053 hdrlen = xsnprintf((char *)hdr, sizeof(hdr), "%s %lu",
1054 type_name(type), (unsigned long)dat->len) + 1;
1055 the_hash_algo->init_fn(&c);
1056 the_hash_algo->update_fn(&c, hdr, hdrlen);
1057 the_hash_algo->update_fn(&c, dat->buf, dat->len);
1058 the_hash_algo->final_fn(oid.hash, &c);
1059 if (oidout)
1060 oidcpy(oidout, &oid);
1062 e = insert_object(&oid);
1063 if (mark)
1064 insert_mark(mark, e);
1065 if (e->idx.offset) {
1066 duplicate_count_by_type[type]++;
1067 return 1;
1068 } else if (find_sha1_pack(oid.hash, packed_git)) {
1069 e->type = type;
1070 e->pack_id = MAX_PACK_ID;
1071 e->idx.offset = 1; /* just not zero! */
1072 duplicate_count_by_type[type]++;
1073 return 1;
1076 if (last && last->data.buf && last->depth < max_depth
1077 && dat->len > the_hash_algo->rawsz) {
1079 delta_count_attempts_by_type[type]++;
1080 delta = diff_delta(last->data.buf, last->data.len,
1081 dat->buf, dat->len,
1082 &deltalen, dat->len - the_hash_algo->rawsz);
1083 } else
1084 delta = NULL;
1086 git_deflate_init(&s, pack_compression_level);
1087 if (delta) {
1088 s.next_in = delta;
1089 s.avail_in = deltalen;
1090 } else {
1091 s.next_in = (void *)dat->buf;
1092 s.avail_in = dat->len;
1094 s.avail_out = git_deflate_bound(&s, s.avail_in);
1095 s.next_out = out = xmalloc(s.avail_out);
1096 while (git_deflate(&s, Z_FINISH) == Z_OK)
1097 ; /* nothing */
1098 git_deflate_end(&s);
1100 /* Determine if we should auto-checkpoint. */
1101 if ((max_packsize && (pack_size + 60 + s.total_out) > max_packsize)
1102 || (pack_size + 60 + s.total_out) < pack_size) {
1104 /* This new object needs to *not* have the current pack_id. */
1105 e->pack_id = pack_id + 1;
1106 cycle_packfile();
1108 /* We cannot carry a delta into the new pack. */
1109 if (delta) {
1110 FREE_AND_NULL(delta);
1112 git_deflate_init(&s, pack_compression_level);
1113 s.next_in = (void *)dat->buf;
1114 s.avail_in = dat->len;
1115 s.avail_out = git_deflate_bound(&s, s.avail_in);
1116 s.next_out = out = xrealloc(out, s.avail_out);
1117 while (git_deflate(&s, Z_FINISH) == Z_OK)
1118 ; /* nothing */
1119 git_deflate_end(&s);
1123 e->type = type;
1124 e->pack_id = pack_id;
1125 e->idx.offset = pack_size;
1126 object_count++;
1127 object_count_by_type[type]++;
1129 crc32_begin(pack_file);
1131 if (delta) {
1132 off_t ofs = e->idx.offset - last->offset;
1133 unsigned pos = sizeof(hdr) - 1;
1135 delta_count_by_type[type]++;
1136 e->depth = last->depth + 1;
1138 hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1139 OBJ_OFS_DELTA, deltalen);
1140 hashwrite(pack_file, hdr, hdrlen);
1141 pack_size += hdrlen;
1143 hdr[pos] = ofs & 127;
1144 while (ofs >>= 7)
1145 hdr[--pos] = 128 | (--ofs & 127);
1146 hashwrite(pack_file, hdr + pos, sizeof(hdr) - pos);
1147 pack_size += sizeof(hdr) - pos;
1148 } else {
1149 e->depth = 0;
1150 hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1151 type, dat->len);
1152 hashwrite(pack_file, hdr, hdrlen);
1153 pack_size += hdrlen;
1156 hashwrite(pack_file, out, s.total_out);
1157 pack_size += s.total_out;
1159 e->idx.crc32 = crc32_end(pack_file);
1161 free(out);
1162 free(delta);
1163 if (last) {
1164 if (last->no_swap) {
1165 last->data = *dat;
1166 } else {
1167 strbuf_swap(&last->data, dat);
1169 last->offset = e->idx.offset;
1170 last->depth = e->depth;
1172 return 0;
1175 static void truncate_pack(struct hashfile_checkpoint *checkpoint)
1177 if (hashfile_truncate(pack_file, checkpoint))
1178 die_errno("cannot truncate pack to skip duplicate");
1179 pack_size = checkpoint->offset;
1182 static void stream_blob(uintmax_t len, struct object_id *oidout, uintmax_t mark)
1184 size_t in_sz = 64 * 1024, out_sz = 64 * 1024;
1185 unsigned char *in_buf = xmalloc(in_sz);
1186 unsigned char *out_buf = xmalloc(out_sz);
1187 struct object_entry *e;
1188 struct object_id oid;
1189 unsigned long hdrlen;
1190 off_t offset;
1191 git_hash_ctx c;
1192 git_zstream s;
1193 struct hashfile_checkpoint checkpoint;
1194 int status = Z_OK;
1196 /* Determine if we should auto-checkpoint. */
1197 if ((max_packsize && (pack_size + 60 + len) > max_packsize)
1198 || (pack_size + 60 + len) < pack_size)
1199 cycle_packfile();
1201 hashfile_checkpoint(pack_file, &checkpoint);
1202 offset = checkpoint.offset;
1204 hdrlen = xsnprintf((char *)out_buf, out_sz, "blob %" PRIuMAX, len) + 1;
1206 the_hash_algo->init_fn(&c);
1207 the_hash_algo->update_fn(&c, out_buf, hdrlen);
1209 crc32_begin(pack_file);
1211 git_deflate_init(&s, pack_compression_level);
1213 hdrlen = encode_in_pack_object_header(out_buf, out_sz, OBJ_BLOB, len);
1215 s.next_out = out_buf + hdrlen;
1216 s.avail_out = out_sz - hdrlen;
1218 while (status != Z_STREAM_END) {
1219 if (0 < len && !s.avail_in) {
1220 size_t cnt = in_sz < len ? in_sz : (size_t)len;
1221 size_t n = fread(in_buf, 1, cnt, stdin);
1222 if (!n && feof(stdin))
1223 die("EOF in data (%" PRIuMAX " bytes remaining)", len);
1225 the_hash_algo->update_fn(&c, in_buf, n);
1226 s.next_in = in_buf;
1227 s.avail_in = n;
1228 len -= n;
1231 status = git_deflate(&s, len ? 0 : Z_FINISH);
1233 if (!s.avail_out || status == Z_STREAM_END) {
1234 size_t n = s.next_out - out_buf;
1235 hashwrite(pack_file, out_buf, n);
1236 pack_size += n;
1237 s.next_out = out_buf;
1238 s.avail_out = out_sz;
1241 switch (status) {
1242 case Z_OK:
1243 case Z_BUF_ERROR:
1244 case Z_STREAM_END:
1245 continue;
1246 default:
1247 die("unexpected deflate failure: %d", status);
1250 git_deflate_end(&s);
1251 the_hash_algo->final_fn(oid.hash, &c);
1253 if (oidout)
1254 oidcpy(oidout, &oid);
1256 e = insert_object(&oid);
1258 if (mark)
1259 insert_mark(mark, e);
1261 if (e->idx.offset) {
1262 duplicate_count_by_type[OBJ_BLOB]++;
1263 truncate_pack(&checkpoint);
1265 } else if (find_sha1_pack(oid.hash, packed_git)) {
1266 e->type = OBJ_BLOB;
1267 e->pack_id = MAX_PACK_ID;
1268 e->idx.offset = 1; /* just not zero! */
1269 duplicate_count_by_type[OBJ_BLOB]++;
1270 truncate_pack(&checkpoint);
1272 } else {
1273 e->depth = 0;
1274 e->type = OBJ_BLOB;
1275 e->pack_id = pack_id;
1276 e->idx.offset = offset;
1277 e->idx.crc32 = crc32_end(pack_file);
1278 object_count++;
1279 object_count_by_type[OBJ_BLOB]++;
1282 free(in_buf);
1283 free(out_buf);
1286 /* All calls must be guarded by find_object() or find_mark() to
1287 * ensure the 'struct object_entry' passed was written by this
1288 * process instance. We unpack the entry by the offset, avoiding
1289 * the need for the corresponding .idx file. This unpacking rule
1290 * works because we only use OBJ_REF_DELTA within the packfiles
1291 * created by fast-import.
1293 * oe must not be NULL. Such an oe usually comes from giving
1294 * an unknown SHA-1 to find_object() or an undefined mark to
1295 * find_mark(). Callers must test for this condition and use
1296 * the standard read_sha1_file() when it happens.
1298 * oe->pack_id must not be MAX_PACK_ID. Such an oe is usually from
1299 * find_mark(), where the mark was reloaded from an existing marks
1300 * file and is referencing an object that this fast-import process
1301 * instance did not write out to a packfile. Callers must test for
1302 * this condition and use read_sha1_file() instead.
1304 static void *gfi_unpack_entry(
1305 struct object_entry *oe,
1306 unsigned long *sizep)
1308 enum object_type type;
1309 struct packed_git *p = all_packs[oe->pack_id];
1310 if (p == pack_data && p->pack_size < (pack_size + the_hash_algo->rawsz)) {
1311 /* The object is stored in the packfile we are writing to
1312 * and we have modified it since the last time we scanned
1313 * back to read a previously written object. If an old
1314 * window covered [p->pack_size, p->pack_size + rawsz) its
1315 * data is stale and is not valid. Closing all windows
1316 * and updating the packfile length ensures we can read
1317 * the newly written data.
1319 close_pack_windows(p);
1320 hashflush(pack_file);
1322 /* We have to offer rawsz bytes additional on the end of
1323 * the packfile as the core unpacker code assumes the
1324 * footer is present at the file end and must promise
1325 * at least rawsz bytes within any window it maps. But
1326 * we don't actually create the footer here.
1328 p->pack_size = pack_size + the_hash_algo->rawsz;
1330 return unpack_entry(p, oe->idx.offset, &type, sizep);
1333 static const char *get_mode(const char *str, uint16_t *modep)
1335 unsigned char c;
1336 uint16_t mode = 0;
1338 while ((c = *str++) != ' ') {
1339 if (c < '0' || c > '7')
1340 return NULL;
1341 mode = (mode << 3) + (c - '0');
1343 *modep = mode;
1344 return str;
1347 static void load_tree(struct tree_entry *root)
1349 struct object_id *oid = &root->versions[1].oid;
1350 struct object_entry *myoe;
1351 struct tree_content *t;
1352 unsigned long size;
1353 char *buf;
1354 const char *c;
1356 root->tree = t = new_tree_content(8);
1357 if (is_null_oid(oid))
1358 return;
1360 myoe = find_object(oid);
1361 if (myoe && myoe->pack_id != MAX_PACK_ID) {
1362 if (myoe->type != OBJ_TREE)
1363 die("Not a tree: %s", oid_to_hex(oid));
1364 t->delta_depth = myoe->depth;
1365 buf = gfi_unpack_entry(myoe, &size);
1366 if (!buf)
1367 die("Can't load tree %s", oid_to_hex(oid));
1368 } else {
1369 enum object_type type;
1370 buf = read_sha1_file(oid->hash, &type, &size);
1371 if (!buf || type != OBJ_TREE)
1372 die("Can't load tree %s", oid_to_hex(oid));
1375 c = buf;
1376 while (c != (buf + size)) {
1377 struct tree_entry *e = new_tree_entry();
1379 if (t->entry_count == t->entry_capacity)
1380 root->tree = t = grow_tree_content(t, t->entry_count);
1381 t->entries[t->entry_count++] = e;
1383 e->tree = NULL;
1384 c = get_mode(c, &e->versions[1].mode);
1385 if (!c)
1386 die("Corrupt mode in %s", oid_to_hex(oid));
1387 e->versions[0].mode = e->versions[1].mode;
1388 e->name = to_atom(c, strlen(c));
1389 c += e->name->str_len + 1;
1390 hashcpy(e->versions[0].oid.hash, (unsigned char *)c);
1391 hashcpy(e->versions[1].oid.hash, (unsigned char *)c);
1392 c += GIT_SHA1_RAWSZ;
1394 free(buf);
1397 static int tecmp0 (const void *_a, const void *_b)
1399 struct tree_entry *a = *((struct tree_entry**)_a);
1400 struct tree_entry *b = *((struct tree_entry**)_b);
1401 return base_name_compare(
1402 a->name->str_dat, a->name->str_len, a->versions[0].mode,
1403 b->name->str_dat, b->name->str_len, b->versions[0].mode);
1406 static int tecmp1 (const void *_a, const void *_b)
1408 struct tree_entry *a = *((struct tree_entry**)_a);
1409 struct tree_entry *b = *((struct tree_entry**)_b);
1410 return base_name_compare(
1411 a->name->str_dat, a->name->str_len, a->versions[1].mode,
1412 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1415 static void mktree(struct tree_content *t, int v, struct strbuf *b)
1417 size_t maxlen = 0;
1418 unsigned int i;
1420 if (!v)
1421 QSORT(t->entries, t->entry_count, tecmp0);
1422 else
1423 QSORT(t->entries, t->entry_count, tecmp1);
1425 for (i = 0; i < t->entry_count; i++) {
1426 if (t->entries[i]->versions[v].mode)
1427 maxlen += t->entries[i]->name->str_len + 34;
1430 strbuf_reset(b);
1431 strbuf_grow(b, maxlen);
1432 for (i = 0; i < t->entry_count; i++) {
1433 struct tree_entry *e = t->entries[i];
1434 if (!e->versions[v].mode)
1435 continue;
1436 strbuf_addf(b, "%o %s%c",
1437 (unsigned int)(e->versions[v].mode & ~NO_DELTA),
1438 e->name->str_dat, '\0');
1439 strbuf_add(b, e->versions[v].oid.hash, GIT_SHA1_RAWSZ);
1443 static void store_tree(struct tree_entry *root)
1445 struct tree_content *t;
1446 unsigned int i, j, del;
1447 struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1448 struct object_entry *le = NULL;
1450 if (!is_null_oid(&root->versions[1].oid))
1451 return;
1453 if (!root->tree)
1454 load_tree(root);
1455 t = root->tree;
1457 for (i = 0; i < t->entry_count; i++) {
1458 if (t->entries[i]->tree)
1459 store_tree(t->entries[i]);
1462 if (!(root->versions[0].mode & NO_DELTA))
1463 le = find_object(&root->versions[0].oid);
1464 if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1465 mktree(t, 0, &old_tree);
1466 lo.data = old_tree;
1467 lo.offset = le->idx.offset;
1468 lo.depth = t->delta_depth;
1471 mktree(t, 1, &new_tree);
1472 store_object(OBJ_TREE, &new_tree, &lo, &root->versions[1].oid, 0);
1474 t->delta_depth = lo.depth;
1475 for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1476 struct tree_entry *e = t->entries[i];
1477 if (e->versions[1].mode) {
1478 e->versions[0].mode = e->versions[1].mode;
1479 oidcpy(&e->versions[0].oid, &e->versions[1].oid);
1480 t->entries[j++] = e;
1481 } else {
1482 release_tree_entry(e);
1483 del++;
1486 t->entry_count -= del;
1489 static void tree_content_replace(
1490 struct tree_entry *root,
1491 const struct object_id *oid,
1492 const uint16_t mode,
1493 struct tree_content *newtree)
1495 if (!S_ISDIR(mode))
1496 die("Root cannot be a non-directory");
1497 oidclr(&root->versions[0].oid);
1498 oidcpy(&root->versions[1].oid, oid);
1499 if (root->tree)
1500 release_tree_content_recursive(root->tree);
1501 root->tree = newtree;
1504 static int tree_content_set(
1505 struct tree_entry *root,
1506 const char *p,
1507 const struct object_id *oid,
1508 const uint16_t mode,
1509 struct tree_content *subtree)
1511 struct tree_content *t;
1512 const char *slash1;
1513 unsigned int i, n;
1514 struct tree_entry *e;
1516 slash1 = strchrnul(p, '/');
1517 n = slash1 - p;
1518 if (!n)
1519 die("Empty path component found in input");
1520 if (!*slash1 && !S_ISDIR(mode) && subtree)
1521 die("Non-directories cannot have subtrees");
1523 if (!root->tree)
1524 load_tree(root);
1525 t = root->tree;
1526 for (i = 0; i < t->entry_count; i++) {
1527 e = t->entries[i];
1528 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1529 if (!*slash1) {
1530 if (!S_ISDIR(mode)
1531 && e->versions[1].mode == mode
1532 && !oidcmp(&e->versions[1].oid, oid))
1533 return 0;
1534 e->versions[1].mode = mode;
1535 oidcpy(&e->versions[1].oid, oid);
1536 if (e->tree)
1537 release_tree_content_recursive(e->tree);
1538 e->tree = subtree;
1541 * We need to leave e->versions[0].sha1 alone
1542 * to avoid modifying the preimage tree used
1543 * when writing out the parent directory.
1544 * But after replacing the subdir with a
1545 * completely different one, it's not a good
1546 * delta base any more, and besides, we've
1547 * thrown away the tree entries needed to
1548 * make a delta against it.
1550 * So let's just explicitly disable deltas
1551 * for the subtree.
1553 if (S_ISDIR(e->versions[0].mode))
1554 e->versions[0].mode |= NO_DELTA;
1556 oidclr(&root->versions[1].oid);
1557 return 1;
1559 if (!S_ISDIR(e->versions[1].mode)) {
1560 e->tree = new_tree_content(8);
1561 e->versions[1].mode = S_IFDIR;
1563 if (!e->tree)
1564 load_tree(e);
1565 if (tree_content_set(e, slash1 + 1, oid, mode, subtree)) {
1566 oidclr(&root->versions[1].oid);
1567 return 1;
1569 return 0;
1573 if (t->entry_count == t->entry_capacity)
1574 root->tree = t = grow_tree_content(t, t->entry_count);
1575 e = new_tree_entry();
1576 e->name = to_atom(p, n);
1577 e->versions[0].mode = 0;
1578 oidclr(&e->versions[0].oid);
1579 t->entries[t->entry_count++] = e;
1580 if (*slash1) {
1581 e->tree = new_tree_content(8);
1582 e->versions[1].mode = S_IFDIR;
1583 tree_content_set(e, slash1 + 1, oid, mode, subtree);
1584 } else {
1585 e->tree = subtree;
1586 e->versions[1].mode = mode;
1587 oidcpy(&e->versions[1].oid, oid);
1589 oidclr(&root->versions[1].oid);
1590 return 1;
1593 static int tree_content_remove(
1594 struct tree_entry *root,
1595 const char *p,
1596 struct tree_entry *backup_leaf,
1597 int allow_root)
1599 struct tree_content *t;
1600 const char *slash1;
1601 unsigned int i, n;
1602 struct tree_entry *e;
1604 slash1 = strchrnul(p, '/');
1605 n = slash1 - p;
1607 if (!root->tree)
1608 load_tree(root);
1610 if (!*p && allow_root) {
1611 e = root;
1612 goto del_entry;
1615 t = root->tree;
1616 for (i = 0; i < t->entry_count; i++) {
1617 e = t->entries[i];
1618 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1619 if (*slash1 && !S_ISDIR(e->versions[1].mode))
1621 * If p names a file in some subdirectory, and a
1622 * file or symlink matching the name of the
1623 * parent directory of p exists, then p cannot
1624 * exist and need not be deleted.
1626 return 1;
1627 if (!*slash1 || !S_ISDIR(e->versions[1].mode))
1628 goto del_entry;
1629 if (!e->tree)
1630 load_tree(e);
1631 if (tree_content_remove(e, slash1 + 1, backup_leaf, 0)) {
1632 for (n = 0; n < e->tree->entry_count; n++) {
1633 if (e->tree->entries[n]->versions[1].mode) {
1634 oidclr(&root->versions[1].oid);
1635 return 1;
1638 backup_leaf = NULL;
1639 goto del_entry;
1641 return 0;
1644 return 0;
1646 del_entry:
1647 if (backup_leaf)
1648 memcpy(backup_leaf, e, sizeof(*backup_leaf));
1649 else if (e->tree)
1650 release_tree_content_recursive(e->tree);
1651 e->tree = NULL;
1652 e->versions[1].mode = 0;
1653 oidclr(&e->versions[1].oid);
1654 oidclr(&root->versions[1].oid);
1655 return 1;
1658 static int tree_content_get(
1659 struct tree_entry *root,
1660 const char *p,
1661 struct tree_entry *leaf,
1662 int allow_root)
1664 struct tree_content *t;
1665 const char *slash1;
1666 unsigned int i, n;
1667 struct tree_entry *e;
1669 slash1 = strchrnul(p, '/');
1670 n = slash1 - p;
1671 if (!n && !allow_root)
1672 die("Empty path component found in input");
1674 if (!root->tree)
1675 load_tree(root);
1677 if (!n) {
1678 e = root;
1679 goto found_entry;
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)
1687 goto found_entry;
1688 if (!S_ISDIR(e->versions[1].mode))
1689 return 0;
1690 if (!e->tree)
1691 load_tree(e);
1692 return tree_content_get(e, slash1 + 1, leaf, 0);
1695 return 0;
1697 found_entry:
1698 memcpy(leaf, e, sizeof(*leaf));
1699 if (e->tree && is_null_oid(&e->versions[1].oid))
1700 leaf->tree = dup_tree_content(e->tree);
1701 else
1702 leaf->tree = NULL;
1703 return 1;
1706 static int update_branch(struct branch *b)
1708 static const char *msg = "fast-import";
1709 struct ref_transaction *transaction;
1710 struct object_id old_oid;
1711 struct strbuf err = STRBUF_INIT;
1713 if (is_null_oid(&b->oid)) {
1714 if (b->delete)
1715 delete_ref(NULL, b->name, NULL, 0);
1716 return 0;
1718 if (read_ref(b->name, &old_oid))
1719 oidclr(&old_oid);
1720 if (!force_update && !is_null_oid(&old_oid)) {
1721 struct commit *old_cmit, *new_cmit;
1723 old_cmit = lookup_commit_reference_gently(&old_oid, 0);
1724 new_cmit = lookup_commit_reference_gently(&b->oid, 0);
1725 if (!old_cmit || !new_cmit)
1726 return error("Branch %s is missing commits.", b->name);
1728 if (!in_merge_bases(old_cmit, new_cmit)) {
1729 warning("Not updating %s"
1730 " (new tip %s does not contain %s)",
1731 b->name, oid_to_hex(&b->oid),
1732 oid_to_hex(&old_oid));
1733 return -1;
1736 transaction = ref_transaction_begin(&err);
1737 if (!transaction ||
1738 ref_transaction_update(transaction, b->name, &b->oid, &old_oid,
1739 0, msg, &err) ||
1740 ref_transaction_commit(transaction, &err)) {
1741 ref_transaction_free(transaction);
1742 error("%s", err.buf);
1743 strbuf_release(&err);
1744 return -1;
1746 ref_transaction_free(transaction);
1747 strbuf_release(&err);
1748 return 0;
1751 static void dump_branches(void)
1753 unsigned int i;
1754 struct branch *b;
1756 for (i = 0; i < branch_table_sz; i++) {
1757 for (b = branch_table[i]; b; b = b->table_next_branch)
1758 failure |= update_branch(b);
1762 static void dump_tags(void)
1764 static const char *msg = "fast-import";
1765 struct tag *t;
1766 struct strbuf ref_name = STRBUF_INIT;
1767 struct strbuf err = STRBUF_INIT;
1768 struct ref_transaction *transaction;
1770 transaction = ref_transaction_begin(&err);
1771 if (!transaction) {
1772 failure |= error("%s", err.buf);
1773 goto cleanup;
1775 for (t = first_tag; t; t = t->next_tag) {
1776 strbuf_reset(&ref_name);
1777 strbuf_addf(&ref_name, "refs/tags/%s", t->name);
1779 if (ref_transaction_update(transaction, ref_name.buf,
1780 &t->oid, NULL, 0, msg, &err)) {
1781 failure |= error("%s", err.buf);
1782 goto cleanup;
1785 if (ref_transaction_commit(transaction, &err))
1786 failure |= error("%s", err.buf);
1788 cleanup:
1789 ref_transaction_free(transaction);
1790 strbuf_release(&ref_name);
1791 strbuf_release(&err);
1794 static void dump_marks_helper(FILE *f,
1795 uintmax_t base,
1796 struct mark_set *m)
1798 uintmax_t k;
1799 if (m->shift) {
1800 for (k = 0; k < 1024; k++) {
1801 if (m->data.sets[k])
1802 dump_marks_helper(f, base + (k << m->shift),
1803 m->data.sets[k]);
1805 } else {
1806 for (k = 0; k < 1024; k++) {
1807 if (m->data.marked[k])
1808 fprintf(f, ":%" PRIuMAX " %s\n", base + k,
1809 oid_to_hex(&m->data.marked[k]->idx.oid));
1814 static void dump_marks(void)
1816 static struct lock_file mark_lock;
1817 FILE *f;
1819 if (!export_marks_file || (import_marks_file && !import_marks_file_done))
1820 return;
1822 if (hold_lock_file_for_update(&mark_lock, export_marks_file, 0) < 0) {
1823 failure |= error_errno("Unable to write marks file %s",
1824 export_marks_file);
1825 return;
1828 f = fdopen_lock_file(&mark_lock, "w");
1829 if (!f) {
1830 int saved_errno = errno;
1831 rollback_lock_file(&mark_lock);
1832 failure |= error("Unable to write marks file %s: %s",
1833 export_marks_file, strerror(saved_errno));
1834 return;
1837 dump_marks_helper(f, 0, marks);
1838 if (commit_lock_file(&mark_lock)) {
1839 failure |= error_errno("Unable to write file %s",
1840 export_marks_file);
1841 return;
1845 static void read_marks(void)
1847 char line[512];
1848 FILE *f = fopen(import_marks_file, "r");
1849 if (f)
1851 else if (import_marks_file_ignore_missing && errno == ENOENT)
1852 goto done; /* Marks file does not exist */
1853 else
1854 die_errno("cannot read '%s'", import_marks_file);
1855 while (fgets(line, sizeof(line), f)) {
1856 uintmax_t mark;
1857 char *end;
1858 struct object_id oid;
1859 struct object_entry *e;
1861 end = strchr(line, '\n');
1862 if (line[0] != ':' || !end)
1863 die("corrupt mark line: %s", line);
1864 *end = 0;
1865 mark = strtoumax(line + 1, &end, 10);
1866 if (!mark || end == line + 1
1867 || *end != ' ' || get_oid_hex(end + 1, &oid))
1868 die("corrupt mark line: %s", line);
1869 e = find_object(&oid);
1870 if (!e) {
1871 enum object_type type = sha1_object_info(oid.hash, NULL);
1872 if (type < 0)
1873 die("object not found: %s", oid_to_hex(&oid));
1874 e = insert_object(&oid);
1875 e->type = type;
1876 e->pack_id = MAX_PACK_ID;
1877 e->idx.offset = 1; /* just not zero! */
1879 insert_mark(mark, e);
1881 fclose(f);
1882 done:
1883 import_marks_file_done = 1;
1887 static int read_next_command(void)
1889 static int stdin_eof = 0;
1891 if (stdin_eof) {
1892 unread_command_buf = 0;
1893 return EOF;
1896 for (;;) {
1897 const char *p;
1899 if (unread_command_buf) {
1900 unread_command_buf = 0;
1901 } else {
1902 struct recent_command *rc;
1904 strbuf_detach(&command_buf, NULL);
1905 stdin_eof = strbuf_getline_lf(&command_buf, stdin);
1906 if (stdin_eof)
1907 return EOF;
1909 if (!seen_data_command
1910 && !starts_with(command_buf.buf, "feature ")
1911 && !starts_with(command_buf.buf, "option ")) {
1912 parse_argv();
1915 rc = rc_free;
1916 if (rc)
1917 rc_free = rc->next;
1918 else {
1919 rc = cmd_hist.next;
1920 cmd_hist.next = rc->next;
1921 cmd_hist.next->prev = &cmd_hist;
1922 free(rc->buf);
1925 rc->buf = command_buf.buf;
1926 rc->prev = cmd_tail;
1927 rc->next = cmd_hist.prev;
1928 rc->prev->next = rc;
1929 cmd_tail = rc;
1931 if (skip_prefix(command_buf.buf, "get-mark ", &p)) {
1932 parse_get_mark(p);
1933 continue;
1935 if (skip_prefix(command_buf.buf, "cat-blob ", &p)) {
1936 parse_cat_blob(p);
1937 continue;
1939 if (command_buf.buf[0] == '#')
1940 continue;
1941 return 0;
1945 static void skip_optional_lf(void)
1947 int term_char = fgetc(stdin);
1948 if (term_char != '\n' && term_char != EOF)
1949 ungetc(term_char, stdin);
1952 static void parse_mark(void)
1954 const char *v;
1955 if (skip_prefix(command_buf.buf, "mark :", &v)) {
1956 next_mark = strtoumax(v, NULL, 10);
1957 read_next_command();
1959 else
1960 next_mark = 0;
1963 static int parse_data(struct strbuf *sb, uintmax_t limit, uintmax_t *len_res)
1965 const char *data;
1966 strbuf_reset(sb);
1968 if (!skip_prefix(command_buf.buf, "data ", &data))
1969 die("Expected 'data n' command, found: %s", command_buf.buf);
1971 if (skip_prefix(data, "<<", &data)) {
1972 char *term = xstrdup(data);
1973 size_t term_len = command_buf.len - (data - command_buf.buf);
1975 strbuf_detach(&command_buf, NULL);
1976 for (;;) {
1977 if (strbuf_getline_lf(&command_buf, stdin) == EOF)
1978 die("EOF in data (terminator '%s' not found)", term);
1979 if (term_len == command_buf.len
1980 && !strcmp(term, command_buf.buf))
1981 break;
1982 strbuf_addbuf(sb, &command_buf);
1983 strbuf_addch(sb, '\n');
1985 free(term);
1987 else {
1988 uintmax_t len = strtoumax(data, NULL, 10);
1989 size_t n = 0, length = (size_t)len;
1991 if (limit && limit < len) {
1992 *len_res = len;
1993 return 0;
1995 if (length < len)
1996 die("data is too large to use in this context");
1998 while (n < length) {
1999 size_t s = strbuf_fread(sb, length - n, stdin);
2000 if (!s && feof(stdin))
2001 die("EOF in data (%lu bytes remaining)",
2002 (unsigned long)(length - n));
2003 n += s;
2007 skip_optional_lf();
2008 return 1;
2011 static int validate_raw_date(const char *src, struct strbuf *result)
2013 const char *orig_src = src;
2014 char *endp;
2015 unsigned long num;
2017 errno = 0;
2019 num = strtoul(src, &endp, 10);
2020 /* NEEDSWORK: perhaps check for reasonable values? */
2021 if (errno || endp == src || *endp != ' ')
2022 return -1;
2024 src = endp + 1;
2025 if (*src != '-' && *src != '+')
2026 return -1;
2028 num = strtoul(src + 1, &endp, 10);
2029 if (errno || endp == src + 1 || *endp || 1400 < num)
2030 return -1;
2032 strbuf_addstr(result, orig_src);
2033 return 0;
2036 static char *parse_ident(const char *buf)
2038 const char *ltgt;
2039 size_t name_len;
2040 struct strbuf ident = STRBUF_INIT;
2042 /* ensure there is a space delimiter even if there is no name */
2043 if (*buf == '<')
2044 --buf;
2046 ltgt = buf + strcspn(buf, "<>");
2047 if (*ltgt != '<')
2048 die("Missing < in ident string: %s", buf);
2049 if (ltgt != buf && ltgt[-1] != ' ')
2050 die("Missing space before < in ident string: %s", buf);
2051 ltgt = ltgt + 1 + strcspn(ltgt + 1, "<>");
2052 if (*ltgt != '>')
2053 die("Missing > in ident string: %s", buf);
2054 ltgt++;
2055 if (*ltgt != ' ')
2056 die("Missing space after > in ident string: %s", buf);
2057 ltgt++;
2058 name_len = ltgt - buf;
2059 strbuf_add(&ident, buf, name_len);
2061 switch (whenspec) {
2062 case WHENSPEC_RAW:
2063 if (validate_raw_date(ltgt, &ident) < 0)
2064 die("Invalid raw date \"%s\" in ident: %s", ltgt, buf);
2065 break;
2066 case WHENSPEC_RFC2822:
2067 if (parse_date(ltgt, &ident) < 0)
2068 die("Invalid rfc2822 date \"%s\" in ident: %s", ltgt, buf);
2069 break;
2070 case WHENSPEC_NOW:
2071 if (strcmp("now", ltgt))
2072 die("Date in ident must be 'now': %s", buf);
2073 datestamp(&ident);
2074 break;
2077 return strbuf_detach(&ident, NULL);
2080 static void parse_and_store_blob(
2081 struct last_object *last,
2082 struct object_id *oidout,
2083 uintmax_t mark)
2085 static struct strbuf buf = STRBUF_INIT;
2086 uintmax_t len;
2088 if (parse_data(&buf, big_file_threshold, &len))
2089 store_object(OBJ_BLOB, &buf, last, oidout, mark);
2090 else {
2091 if (last) {
2092 strbuf_release(&last->data);
2093 last->offset = 0;
2094 last->depth = 0;
2096 stream_blob(len, oidout, mark);
2097 skip_optional_lf();
2101 static void parse_new_blob(void)
2103 read_next_command();
2104 parse_mark();
2105 parse_and_store_blob(&last_blob, NULL, next_mark);
2108 static void unload_one_branch(void)
2110 while (cur_active_branches
2111 && cur_active_branches >= max_active_branches) {
2112 uintmax_t min_commit = ULONG_MAX;
2113 struct branch *e, *l = NULL, *p = NULL;
2115 for (e = active_branches; e; e = e->active_next_branch) {
2116 if (e->last_commit < min_commit) {
2117 p = l;
2118 min_commit = e->last_commit;
2120 l = e;
2123 if (p) {
2124 e = p->active_next_branch;
2125 p->active_next_branch = e->active_next_branch;
2126 } else {
2127 e = active_branches;
2128 active_branches = e->active_next_branch;
2130 e->active = 0;
2131 e->active_next_branch = NULL;
2132 if (e->branch_tree.tree) {
2133 release_tree_content_recursive(e->branch_tree.tree);
2134 e->branch_tree.tree = NULL;
2136 cur_active_branches--;
2140 static void load_branch(struct branch *b)
2142 load_tree(&b->branch_tree);
2143 if (!b->active) {
2144 b->active = 1;
2145 b->active_next_branch = active_branches;
2146 active_branches = b;
2147 cur_active_branches++;
2148 branch_load_count++;
2152 static unsigned char convert_num_notes_to_fanout(uintmax_t num_notes)
2154 unsigned char fanout = 0;
2155 while ((num_notes >>= 8))
2156 fanout++;
2157 return fanout;
2160 static void construct_path_with_fanout(const char *hex_sha1,
2161 unsigned char fanout, char *path)
2163 unsigned int i = 0, j = 0;
2164 if (fanout >= the_hash_algo->rawsz)
2165 die("Too large fanout (%u)", fanout);
2166 while (fanout) {
2167 path[i++] = hex_sha1[j++];
2168 path[i++] = hex_sha1[j++];
2169 path[i++] = '/';
2170 fanout--;
2172 memcpy(path + i, hex_sha1 + j, the_hash_algo->hexsz - j);
2173 path[i + the_hash_algo->hexsz - j] = '\0';
2176 static uintmax_t do_change_note_fanout(
2177 struct tree_entry *orig_root, struct tree_entry *root,
2178 char *hex_oid, unsigned int hex_oid_len,
2179 char *fullpath, unsigned int fullpath_len,
2180 unsigned char fanout)
2182 struct tree_content *t;
2183 struct tree_entry *e, leaf;
2184 unsigned int i, tmp_hex_oid_len, tmp_fullpath_len;
2185 uintmax_t num_notes = 0;
2186 struct object_id oid;
2187 char realpath[60];
2189 if (!root->tree)
2190 load_tree(root);
2191 t = root->tree;
2193 for (i = 0; t && i < t->entry_count; i++) {
2194 e = t->entries[i];
2195 tmp_hex_oid_len = hex_oid_len + e->name->str_len;
2196 tmp_fullpath_len = fullpath_len;
2199 * We're interested in EITHER existing note entries (entries
2200 * with exactly 40 hex chars in path, not including directory
2201 * separators), OR directory entries that may contain note
2202 * entries (with < 40 hex chars in path).
2203 * Also, each path component in a note entry must be a multiple
2204 * of 2 chars.
2206 if (!e->versions[1].mode ||
2207 tmp_hex_oid_len > GIT_SHA1_HEXSZ ||
2208 e->name->str_len % 2)
2209 continue;
2211 /* This _may_ be a note entry, or a subdir containing notes */
2212 memcpy(hex_oid + hex_oid_len, e->name->str_dat,
2213 e->name->str_len);
2214 if (tmp_fullpath_len)
2215 fullpath[tmp_fullpath_len++] = '/';
2216 memcpy(fullpath + tmp_fullpath_len, e->name->str_dat,
2217 e->name->str_len);
2218 tmp_fullpath_len += e->name->str_len;
2219 fullpath[tmp_fullpath_len] = '\0';
2221 if (tmp_hex_oid_len == GIT_SHA1_HEXSZ && !get_oid_hex(hex_oid, &oid)) {
2222 /* This is a note entry */
2223 if (fanout == 0xff) {
2224 /* Counting mode, no rename */
2225 num_notes++;
2226 continue;
2228 construct_path_with_fanout(hex_oid, fanout, realpath);
2229 if (!strcmp(fullpath, realpath)) {
2230 /* Note entry is in correct location */
2231 num_notes++;
2232 continue;
2235 /* Rename fullpath to realpath */
2236 if (!tree_content_remove(orig_root, fullpath, &leaf, 0))
2237 die("Failed to remove path %s", fullpath);
2238 tree_content_set(orig_root, realpath,
2239 &leaf.versions[1].oid,
2240 leaf.versions[1].mode,
2241 leaf.tree);
2242 } else if (S_ISDIR(e->versions[1].mode)) {
2243 /* This is a subdir that may contain note entries */
2244 num_notes += do_change_note_fanout(orig_root, e,
2245 hex_oid, tmp_hex_oid_len,
2246 fullpath, tmp_fullpath_len, fanout);
2249 /* The above may have reallocated the current tree_content */
2250 t = root->tree;
2252 return num_notes;
2255 static uintmax_t change_note_fanout(struct tree_entry *root,
2256 unsigned char fanout)
2259 * The size of path is due to one slash between every two hex digits,
2260 * plus the terminating NUL. Note that there is no slash at the end, so
2261 * the number of slashes is one less than half the number of hex
2262 * characters.
2264 char hex_oid[GIT_MAX_HEXSZ], path[GIT_MAX_HEXSZ + (GIT_MAX_HEXSZ / 2) - 1 + 1];
2265 return do_change_note_fanout(root, root, hex_oid, 0, path, 0, fanout);
2269 * Given a pointer into a string, parse a mark reference:
2271 * idnum ::= ':' bigint;
2273 * Return the first character after the value in *endptr.
2275 * Complain if the following character is not what is expected,
2276 * either a space or end of the string.
2278 static uintmax_t parse_mark_ref(const char *p, char **endptr)
2280 uintmax_t mark;
2282 assert(*p == ':');
2283 p++;
2284 mark = strtoumax(p, endptr, 10);
2285 if (*endptr == p)
2286 die("No value after ':' in mark: %s", command_buf.buf);
2287 return mark;
2291 * Parse the mark reference, and complain if this is not the end of
2292 * the string.
2294 static uintmax_t parse_mark_ref_eol(const char *p)
2296 char *end;
2297 uintmax_t mark;
2299 mark = parse_mark_ref(p, &end);
2300 if (*end != '\0')
2301 die("Garbage after mark: %s", command_buf.buf);
2302 return mark;
2306 * Parse the mark reference, demanding a trailing space. Return a
2307 * pointer to the space.
2309 static uintmax_t parse_mark_ref_space(const char **p)
2311 uintmax_t mark;
2312 char *end;
2314 mark = parse_mark_ref(*p, &end);
2315 if (*end++ != ' ')
2316 die("Missing space after mark: %s", command_buf.buf);
2317 *p = end;
2318 return mark;
2321 static void file_change_m(const char *p, struct branch *b)
2323 static struct strbuf uq = STRBUF_INIT;
2324 const char *endp;
2325 struct object_entry *oe;
2326 struct object_id oid;
2327 uint16_t mode, inline_data = 0;
2329 p = get_mode(p, &mode);
2330 if (!p)
2331 die("Corrupt mode: %s", command_buf.buf);
2332 switch (mode) {
2333 case 0644:
2334 case 0755:
2335 mode |= S_IFREG;
2336 case S_IFREG | 0644:
2337 case S_IFREG | 0755:
2338 case S_IFLNK:
2339 case S_IFDIR:
2340 case S_IFGITLINK:
2341 /* ok */
2342 break;
2343 default:
2344 die("Corrupt mode: %s", command_buf.buf);
2347 if (*p == ':') {
2348 oe = find_mark(parse_mark_ref_space(&p));
2349 oidcpy(&oid, &oe->idx.oid);
2350 } else if (skip_prefix(p, "inline ", &p)) {
2351 inline_data = 1;
2352 oe = NULL; /* not used with inline_data, but makes gcc happy */
2353 } else {
2354 if (parse_oid_hex(p, &oid, &p))
2355 die("Invalid dataref: %s", command_buf.buf);
2356 oe = find_object(&oid);
2357 if (*p++ != ' ')
2358 die("Missing space after SHA1: %s", command_buf.buf);
2361 strbuf_reset(&uq);
2362 if (!unquote_c_style(&uq, p, &endp)) {
2363 if (*endp)
2364 die("Garbage after path in: %s", command_buf.buf);
2365 p = uq.buf;
2368 /* Git does not track empty, non-toplevel directories. */
2369 if (S_ISDIR(mode) && is_empty_tree_oid(&oid) && *p) {
2370 tree_content_remove(&b->branch_tree, p, NULL, 0);
2371 return;
2374 if (S_ISGITLINK(mode)) {
2375 if (inline_data)
2376 die("Git links cannot be specified 'inline': %s",
2377 command_buf.buf);
2378 else if (oe) {
2379 if (oe->type != OBJ_COMMIT)
2380 die("Not a commit (actually a %s): %s",
2381 type_name(oe->type), command_buf.buf);
2384 * Accept the sha1 without checking; it expected to be in
2385 * another repository.
2387 } else if (inline_data) {
2388 if (S_ISDIR(mode))
2389 die("Directories cannot be specified 'inline': %s",
2390 command_buf.buf);
2391 if (p != uq.buf) {
2392 strbuf_addstr(&uq, p);
2393 p = uq.buf;
2395 read_next_command();
2396 parse_and_store_blob(&last_blob, &oid, 0);
2397 } else {
2398 enum object_type expected = S_ISDIR(mode) ?
2399 OBJ_TREE: OBJ_BLOB;
2400 enum object_type type = oe ? oe->type :
2401 sha1_object_info(oid.hash, NULL);
2402 if (type < 0)
2403 die("%s not found: %s",
2404 S_ISDIR(mode) ? "Tree" : "Blob",
2405 command_buf.buf);
2406 if (type != expected)
2407 die("Not a %s (actually a %s): %s",
2408 type_name(expected), type_name(type),
2409 command_buf.buf);
2412 if (!*p) {
2413 tree_content_replace(&b->branch_tree, &oid, mode, NULL);
2414 return;
2416 tree_content_set(&b->branch_tree, p, &oid, mode, NULL);
2419 static void file_change_d(const char *p, struct branch *b)
2421 static struct strbuf uq = STRBUF_INIT;
2422 const char *endp;
2424 strbuf_reset(&uq);
2425 if (!unquote_c_style(&uq, p, &endp)) {
2426 if (*endp)
2427 die("Garbage after path in: %s", command_buf.buf);
2428 p = uq.buf;
2430 tree_content_remove(&b->branch_tree, p, NULL, 1);
2433 static void file_change_cr(const char *s, struct branch *b, int rename)
2435 const char *d;
2436 static struct strbuf s_uq = STRBUF_INIT;
2437 static struct strbuf d_uq = STRBUF_INIT;
2438 const char *endp;
2439 struct tree_entry leaf;
2441 strbuf_reset(&s_uq);
2442 if (!unquote_c_style(&s_uq, s, &endp)) {
2443 if (*endp != ' ')
2444 die("Missing space after source: %s", command_buf.buf);
2445 } else {
2446 endp = strchr(s, ' ');
2447 if (!endp)
2448 die("Missing space after source: %s", command_buf.buf);
2449 strbuf_add(&s_uq, s, endp - s);
2451 s = s_uq.buf;
2453 endp++;
2454 if (!*endp)
2455 die("Missing dest: %s", command_buf.buf);
2457 d = endp;
2458 strbuf_reset(&d_uq);
2459 if (!unquote_c_style(&d_uq, d, &endp)) {
2460 if (*endp)
2461 die("Garbage after dest in: %s", command_buf.buf);
2462 d = d_uq.buf;
2465 memset(&leaf, 0, sizeof(leaf));
2466 if (rename)
2467 tree_content_remove(&b->branch_tree, s, &leaf, 1);
2468 else
2469 tree_content_get(&b->branch_tree, s, &leaf, 1);
2470 if (!leaf.versions[1].mode)
2471 die("Path %s not in branch", s);
2472 if (!*d) { /* C "path/to/subdir" "" */
2473 tree_content_replace(&b->branch_tree,
2474 &leaf.versions[1].oid,
2475 leaf.versions[1].mode,
2476 leaf.tree);
2477 return;
2479 tree_content_set(&b->branch_tree, d,
2480 &leaf.versions[1].oid,
2481 leaf.versions[1].mode,
2482 leaf.tree);
2485 static void note_change_n(const char *p, struct branch *b, unsigned char *old_fanout)
2487 static struct strbuf uq = STRBUF_INIT;
2488 struct object_entry *oe;
2489 struct branch *s;
2490 struct object_id oid, commit_oid;
2491 char path[60];
2492 uint16_t inline_data = 0;
2493 unsigned char new_fanout;
2496 * When loading a branch, we don't traverse its tree to count the real
2497 * number of notes (too expensive to do this for all non-note refs).
2498 * This means that recently loaded notes refs might incorrectly have
2499 * b->num_notes == 0, and consequently, old_fanout might be wrong.
2501 * Fix this by traversing the tree and counting the number of notes
2502 * when b->num_notes == 0. If the notes tree is truly empty, the
2503 * calculation should not take long.
2505 if (b->num_notes == 0 && *old_fanout == 0) {
2506 /* Invoke change_note_fanout() in "counting mode". */
2507 b->num_notes = change_note_fanout(&b->branch_tree, 0xff);
2508 *old_fanout = convert_num_notes_to_fanout(b->num_notes);
2511 /* Now parse the notemodify command. */
2512 /* <dataref> or 'inline' */
2513 if (*p == ':') {
2514 oe = find_mark(parse_mark_ref_space(&p));
2515 oidcpy(&oid, &oe->idx.oid);
2516 } else if (skip_prefix(p, "inline ", &p)) {
2517 inline_data = 1;
2518 oe = NULL; /* not used with inline_data, but makes gcc happy */
2519 } else {
2520 if (parse_oid_hex(p, &oid, &p))
2521 die("Invalid dataref: %s", command_buf.buf);
2522 oe = find_object(&oid);
2523 if (*p++ != ' ')
2524 die("Missing space after SHA1: %s", command_buf.buf);
2527 /* <commit-ish> */
2528 s = lookup_branch(p);
2529 if (s) {
2530 if (is_null_oid(&s->oid))
2531 die("Can't add a note on empty branch.");
2532 oidcpy(&commit_oid, &s->oid);
2533 } else if (*p == ':') {
2534 uintmax_t commit_mark = parse_mark_ref_eol(p);
2535 struct object_entry *commit_oe = find_mark(commit_mark);
2536 if (commit_oe->type != OBJ_COMMIT)
2537 die("Mark :%" PRIuMAX " not a commit", commit_mark);
2538 oidcpy(&commit_oid, &commit_oe->idx.oid);
2539 } else if (!get_oid(p, &commit_oid)) {
2540 unsigned long size;
2541 char *buf = read_object_with_reference(commit_oid.hash,
2542 commit_type, &size, commit_oid.hash);
2543 if (!buf || size < 46)
2544 die("Not a valid commit: %s", p);
2545 free(buf);
2546 } else
2547 die("Invalid ref name or SHA1 expression: %s", p);
2549 if (inline_data) {
2550 if (p != uq.buf) {
2551 strbuf_addstr(&uq, p);
2552 p = uq.buf;
2554 read_next_command();
2555 parse_and_store_blob(&last_blob, &oid, 0);
2556 } else if (oe) {
2557 if (oe->type != OBJ_BLOB)
2558 die("Not a blob (actually a %s): %s",
2559 type_name(oe->type), command_buf.buf);
2560 } else if (!is_null_oid(&oid)) {
2561 enum object_type type = sha1_object_info(oid.hash, NULL);
2562 if (type < 0)
2563 die("Blob not found: %s", command_buf.buf);
2564 if (type != OBJ_BLOB)
2565 die("Not a blob (actually a %s): %s",
2566 type_name(type), command_buf.buf);
2569 construct_path_with_fanout(oid_to_hex(&commit_oid), *old_fanout, path);
2570 if (tree_content_remove(&b->branch_tree, path, NULL, 0))
2571 b->num_notes--;
2573 if (is_null_oid(&oid))
2574 return; /* nothing to insert */
2576 b->num_notes++;
2577 new_fanout = convert_num_notes_to_fanout(b->num_notes);
2578 construct_path_with_fanout(oid_to_hex(&commit_oid), new_fanout, path);
2579 tree_content_set(&b->branch_tree, path, &oid, S_IFREG | 0644, NULL);
2582 static void file_change_deleteall(struct branch *b)
2584 release_tree_content_recursive(b->branch_tree.tree);
2585 oidclr(&b->branch_tree.versions[0].oid);
2586 oidclr(&b->branch_tree.versions[1].oid);
2587 load_tree(&b->branch_tree);
2588 b->num_notes = 0;
2591 static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2593 if (!buf || size < GIT_SHA1_HEXSZ + 6)
2594 die("Not a valid commit: %s", oid_to_hex(&b->oid));
2595 if (memcmp("tree ", buf, 5)
2596 || get_oid_hex(buf + 5, &b->branch_tree.versions[1].oid))
2597 die("The commit %s is corrupt", oid_to_hex(&b->oid));
2598 oidcpy(&b->branch_tree.versions[0].oid,
2599 &b->branch_tree.versions[1].oid);
2602 static void parse_from_existing(struct branch *b)
2604 if (is_null_oid(&b->oid)) {
2605 oidclr(&b->branch_tree.versions[0].oid);
2606 oidclr(&b->branch_tree.versions[1].oid);
2607 } else {
2608 unsigned long size;
2609 char *buf;
2611 buf = read_object_with_reference(b->oid.hash,
2612 commit_type, &size,
2613 b->oid.hash);
2614 parse_from_commit(b, buf, size);
2615 free(buf);
2619 static int parse_from(struct branch *b)
2621 const char *from;
2622 struct branch *s;
2623 struct object_id oid;
2625 if (!skip_prefix(command_buf.buf, "from ", &from))
2626 return 0;
2628 oidcpy(&oid, &b->branch_tree.versions[1].oid);
2630 s = lookup_branch(from);
2631 if (b == s)
2632 die("Can't create a branch from itself: %s", b->name);
2633 else if (s) {
2634 struct object_id *t = &s->branch_tree.versions[1].oid;
2635 oidcpy(&b->oid, &s->oid);
2636 oidcpy(&b->branch_tree.versions[0].oid, t);
2637 oidcpy(&b->branch_tree.versions[1].oid, t);
2638 } else if (*from == ':') {
2639 uintmax_t idnum = parse_mark_ref_eol(from);
2640 struct object_entry *oe = find_mark(idnum);
2641 if (oe->type != OBJ_COMMIT)
2642 die("Mark :%" PRIuMAX " not a commit", idnum);
2643 if (oidcmp(&b->oid, &oe->idx.oid)) {
2644 oidcpy(&b->oid, &oe->idx.oid);
2645 if (oe->pack_id != MAX_PACK_ID) {
2646 unsigned long size;
2647 char *buf = gfi_unpack_entry(oe, &size);
2648 parse_from_commit(b, buf, size);
2649 free(buf);
2650 } else
2651 parse_from_existing(b);
2653 } else if (!get_oid(from, &b->oid)) {
2654 parse_from_existing(b);
2655 if (is_null_oid(&b->oid))
2656 b->delete = 1;
2658 else
2659 die("Invalid ref name or SHA1 expression: %s", from);
2661 if (b->branch_tree.tree && oidcmp(&oid, &b->branch_tree.versions[1].oid)) {
2662 release_tree_content_recursive(b->branch_tree.tree);
2663 b->branch_tree.tree = NULL;
2666 read_next_command();
2667 return 1;
2670 static struct hash_list *parse_merge(unsigned int *count)
2672 struct hash_list *list = NULL, **tail = &list, *n;
2673 const char *from;
2674 struct branch *s;
2676 *count = 0;
2677 while (skip_prefix(command_buf.buf, "merge ", &from)) {
2678 n = xmalloc(sizeof(*n));
2679 s = lookup_branch(from);
2680 if (s)
2681 oidcpy(&n->oid, &s->oid);
2682 else if (*from == ':') {
2683 uintmax_t idnum = parse_mark_ref_eol(from);
2684 struct object_entry *oe = find_mark(idnum);
2685 if (oe->type != OBJ_COMMIT)
2686 die("Mark :%" PRIuMAX " not a commit", idnum);
2687 oidcpy(&n->oid, &oe->idx.oid);
2688 } else if (!get_oid(from, &n->oid)) {
2689 unsigned long size;
2690 char *buf = read_object_with_reference(n->oid.hash,
2691 commit_type, &size, n->oid.hash);
2692 if (!buf || size < 46)
2693 die("Not a valid commit: %s", from);
2694 free(buf);
2695 } else
2696 die("Invalid ref name or SHA1 expression: %s", from);
2698 n->next = NULL;
2699 *tail = n;
2700 tail = &n->next;
2702 (*count)++;
2703 read_next_command();
2705 return list;
2708 static void parse_new_commit(const char *arg)
2710 static struct strbuf msg = STRBUF_INIT;
2711 struct branch *b;
2712 char *author = NULL;
2713 char *committer = NULL;
2714 struct hash_list *merge_list = NULL;
2715 unsigned int merge_count;
2716 unsigned char prev_fanout, new_fanout;
2717 const char *v;
2719 b = lookup_branch(arg);
2720 if (!b)
2721 b = new_branch(arg);
2723 read_next_command();
2724 parse_mark();
2725 if (skip_prefix(command_buf.buf, "author ", &v)) {
2726 author = parse_ident(v);
2727 read_next_command();
2729 if (skip_prefix(command_buf.buf, "committer ", &v)) {
2730 committer = parse_ident(v);
2731 read_next_command();
2733 if (!committer)
2734 die("Expected committer but didn't get one");
2735 parse_data(&msg, 0, NULL);
2736 read_next_command();
2737 parse_from(b);
2738 merge_list = parse_merge(&merge_count);
2740 /* ensure the branch is active/loaded */
2741 if (!b->branch_tree.tree || !max_active_branches) {
2742 unload_one_branch();
2743 load_branch(b);
2746 prev_fanout = convert_num_notes_to_fanout(b->num_notes);
2748 /* file_change* */
2749 while (command_buf.len > 0) {
2750 if (skip_prefix(command_buf.buf, "M ", &v))
2751 file_change_m(v, b);
2752 else if (skip_prefix(command_buf.buf, "D ", &v))
2753 file_change_d(v, b);
2754 else if (skip_prefix(command_buf.buf, "R ", &v))
2755 file_change_cr(v, b, 1);
2756 else if (skip_prefix(command_buf.buf, "C ", &v))
2757 file_change_cr(v, b, 0);
2758 else if (skip_prefix(command_buf.buf, "N ", &v))
2759 note_change_n(v, b, &prev_fanout);
2760 else if (!strcmp("deleteall", command_buf.buf))
2761 file_change_deleteall(b);
2762 else if (skip_prefix(command_buf.buf, "ls ", &v))
2763 parse_ls(v, b);
2764 else {
2765 unread_command_buf = 1;
2766 break;
2768 if (read_next_command() == EOF)
2769 break;
2772 new_fanout = convert_num_notes_to_fanout(b->num_notes);
2773 if (new_fanout != prev_fanout)
2774 b->num_notes = change_note_fanout(&b->branch_tree, new_fanout);
2776 /* build the tree and the commit */
2777 store_tree(&b->branch_tree);
2778 oidcpy(&b->branch_tree.versions[0].oid,
2779 &b->branch_tree.versions[1].oid);
2781 strbuf_reset(&new_data);
2782 strbuf_addf(&new_data, "tree %s\n",
2783 oid_to_hex(&b->branch_tree.versions[1].oid));
2784 if (!is_null_oid(&b->oid))
2785 strbuf_addf(&new_data, "parent %s\n",
2786 oid_to_hex(&b->oid));
2787 while (merge_list) {
2788 struct hash_list *next = merge_list->next;
2789 strbuf_addf(&new_data, "parent %s\n",
2790 oid_to_hex(&merge_list->oid));
2791 free(merge_list);
2792 merge_list = next;
2794 strbuf_addf(&new_data,
2795 "author %s\n"
2796 "committer %s\n"
2797 "\n",
2798 author ? author : committer, committer);
2799 strbuf_addbuf(&new_data, &msg);
2800 free(author);
2801 free(committer);
2803 if (!store_object(OBJ_COMMIT, &new_data, NULL, &b->oid, next_mark))
2804 b->pack_id = pack_id;
2805 b->last_commit = object_count_by_type[OBJ_COMMIT];
2808 static void parse_new_tag(const char *arg)
2810 static struct strbuf msg = STRBUF_INIT;
2811 const char *from;
2812 char *tagger;
2813 struct branch *s;
2814 struct tag *t;
2815 uintmax_t from_mark = 0;
2816 struct object_id oid;
2817 enum object_type type;
2818 const char *v;
2820 t = mem_pool_alloc(&fi_mem_pool, sizeof(struct tag));
2821 memset(t, 0, sizeof(struct tag));
2822 t->name = pool_strdup(arg);
2823 if (last_tag)
2824 last_tag->next_tag = t;
2825 else
2826 first_tag = t;
2827 last_tag = t;
2828 read_next_command();
2830 /* from ... */
2831 if (!skip_prefix(command_buf.buf, "from ", &from))
2832 die("Expected from command, got %s", command_buf.buf);
2833 s = lookup_branch(from);
2834 if (s) {
2835 if (is_null_oid(&s->oid))
2836 die("Can't tag an empty branch.");
2837 oidcpy(&oid, &s->oid);
2838 type = OBJ_COMMIT;
2839 } else if (*from == ':') {
2840 struct object_entry *oe;
2841 from_mark = parse_mark_ref_eol(from);
2842 oe = find_mark(from_mark);
2843 type = oe->type;
2844 oidcpy(&oid, &oe->idx.oid);
2845 } else if (!get_oid(from, &oid)) {
2846 struct object_entry *oe = find_object(&oid);
2847 if (!oe) {
2848 type = sha1_object_info(oid.hash, NULL);
2849 if (type < 0)
2850 die("Not a valid object: %s", from);
2851 } else
2852 type = oe->type;
2853 } else
2854 die("Invalid ref name or SHA1 expression: %s", from);
2855 read_next_command();
2857 /* tagger ... */
2858 if (skip_prefix(command_buf.buf, "tagger ", &v)) {
2859 tagger = parse_ident(v);
2860 read_next_command();
2861 } else
2862 tagger = NULL;
2864 /* tag payload/message */
2865 parse_data(&msg, 0, NULL);
2867 /* build the tag object */
2868 strbuf_reset(&new_data);
2870 strbuf_addf(&new_data,
2871 "object %s\n"
2872 "type %s\n"
2873 "tag %s\n",
2874 oid_to_hex(&oid), type_name(type), t->name);
2875 if (tagger)
2876 strbuf_addf(&new_data,
2877 "tagger %s\n", tagger);
2878 strbuf_addch(&new_data, '\n');
2879 strbuf_addbuf(&new_data, &msg);
2880 free(tagger);
2882 if (store_object(OBJ_TAG, &new_data, NULL, &t->oid, 0))
2883 t->pack_id = MAX_PACK_ID;
2884 else
2885 t->pack_id = pack_id;
2888 static void parse_reset_branch(const char *arg)
2890 struct branch *b;
2892 b = lookup_branch(arg);
2893 if (b) {
2894 oidclr(&b->oid);
2895 oidclr(&b->branch_tree.versions[0].oid);
2896 oidclr(&b->branch_tree.versions[1].oid);
2897 if (b->branch_tree.tree) {
2898 release_tree_content_recursive(b->branch_tree.tree);
2899 b->branch_tree.tree = NULL;
2902 else
2903 b = new_branch(arg);
2904 read_next_command();
2905 parse_from(b);
2906 if (command_buf.len > 0)
2907 unread_command_buf = 1;
2910 static void cat_blob_write(const char *buf, unsigned long size)
2912 if (write_in_full(cat_blob_fd, buf, size) < 0)
2913 die_errno("Write to frontend failed");
2916 static void cat_blob(struct object_entry *oe, struct object_id *oid)
2918 struct strbuf line = STRBUF_INIT;
2919 unsigned long size;
2920 enum object_type type = 0;
2921 char *buf;
2923 if (!oe || oe->pack_id == MAX_PACK_ID) {
2924 buf = read_sha1_file(oid->hash, &type, &size);
2925 } else {
2926 type = oe->type;
2927 buf = gfi_unpack_entry(oe, &size);
2931 * Output based on batch_one_object() from cat-file.c.
2933 if (type <= 0) {
2934 strbuf_reset(&line);
2935 strbuf_addf(&line, "%s missing\n", oid_to_hex(oid));
2936 cat_blob_write(line.buf, line.len);
2937 strbuf_release(&line);
2938 free(buf);
2939 return;
2941 if (!buf)
2942 die("Can't read object %s", oid_to_hex(oid));
2943 if (type != OBJ_BLOB)
2944 die("Object %s is a %s but a blob was expected.",
2945 oid_to_hex(oid), type_name(type));
2946 strbuf_reset(&line);
2947 strbuf_addf(&line, "%s %s %lu\n", oid_to_hex(oid),
2948 type_name(type), size);
2949 cat_blob_write(line.buf, line.len);
2950 strbuf_release(&line);
2951 cat_blob_write(buf, size);
2952 cat_blob_write("\n", 1);
2953 if (oe && oe->pack_id == pack_id) {
2954 last_blob.offset = oe->idx.offset;
2955 strbuf_attach(&last_blob.data, buf, size, size);
2956 last_blob.depth = oe->depth;
2957 } else
2958 free(buf);
2961 static void parse_get_mark(const char *p)
2963 struct object_entry *oe;
2964 char output[GIT_MAX_HEXSZ + 2];
2966 /* get-mark SP <object> LF */
2967 if (*p != ':')
2968 die("Not a mark: %s", p);
2970 oe = find_mark(parse_mark_ref_eol(p));
2971 if (!oe)
2972 die("Unknown mark: %s", command_buf.buf);
2974 xsnprintf(output, sizeof(output), "%s\n", oid_to_hex(&oe->idx.oid));
2975 cat_blob_write(output, GIT_SHA1_HEXSZ + 1);
2978 static void parse_cat_blob(const char *p)
2980 struct object_entry *oe;
2981 struct object_id oid;
2983 /* cat-blob SP <object> LF */
2984 if (*p == ':') {
2985 oe = find_mark(parse_mark_ref_eol(p));
2986 if (!oe)
2987 die("Unknown mark: %s", command_buf.buf);
2988 oidcpy(&oid, &oe->idx.oid);
2989 } else {
2990 if (parse_oid_hex(p, &oid, &p))
2991 die("Invalid dataref: %s", command_buf.buf);
2992 if (*p)
2993 die("Garbage after SHA1: %s", command_buf.buf);
2994 oe = find_object(&oid);
2997 cat_blob(oe, &oid);
3000 static struct object_entry *dereference(struct object_entry *oe,
3001 struct object_id *oid)
3003 unsigned long size;
3004 char *buf = NULL;
3005 if (!oe) {
3006 enum object_type type = sha1_object_info(oid->hash, NULL);
3007 if (type < 0)
3008 die("object not found: %s", oid_to_hex(oid));
3009 /* cache it! */
3010 oe = insert_object(oid);
3011 oe->type = type;
3012 oe->pack_id = MAX_PACK_ID;
3013 oe->idx.offset = 1;
3015 switch (oe->type) {
3016 case OBJ_TREE: /* easy case. */
3017 return oe;
3018 case OBJ_COMMIT:
3019 case OBJ_TAG:
3020 break;
3021 default:
3022 die("Not a tree-ish: %s", command_buf.buf);
3025 if (oe->pack_id != MAX_PACK_ID) { /* in a pack being written */
3026 buf = gfi_unpack_entry(oe, &size);
3027 } else {
3028 enum object_type unused;
3029 buf = read_sha1_file(oid->hash, &unused, &size);
3031 if (!buf)
3032 die("Can't load object %s", oid_to_hex(oid));
3034 /* Peel one layer. */
3035 switch (oe->type) {
3036 case OBJ_TAG:
3037 if (size < GIT_SHA1_HEXSZ + strlen("object ") ||
3038 get_oid_hex(buf + strlen("object "), oid))
3039 die("Invalid SHA1 in tag: %s", command_buf.buf);
3040 break;
3041 case OBJ_COMMIT:
3042 if (size < GIT_SHA1_HEXSZ + strlen("tree ") ||
3043 get_oid_hex(buf + strlen("tree "), oid))
3044 die("Invalid SHA1 in commit: %s", command_buf.buf);
3047 free(buf);
3048 return find_object(oid);
3051 static struct object_entry *parse_treeish_dataref(const char **p)
3053 struct object_id oid;
3054 struct object_entry *e;
3056 if (**p == ':') { /* <mark> */
3057 e = find_mark(parse_mark_ref_space(p));
3058 if (!e)
3059 die("Unknown mark: %s", command_buf.buf);
3060 oidcpy(&oid, &e->idx.oid);
3061 } else { /* <sha1> */
3062 if (parse_oid_hex(*p, &oid, p))
3063 die("Invalid dataref: %s", command_buf.buf);
3064 e = find_object(&oid);
3065 if (*(*p)++ != ' ')
3066 die("Missing space after tree-ish: %s", command_buf.buf);
3069 while (!e || e->type != OBJ_TREE)
3070 e = dereference(e, &oid);
3071 return e;
3074 static void print_ls(int mode, const unsigned char *sha1, const char *path)
3076 static struct strbuf line = STRBUF_INIT;
3078 /* See show_tree(). */
3079 const char *type =
3080 S_ISGITLINK(mode) ? commit_type :
3081 S_ISDIR(mode) ? tree_type :
3082 blob_type;
3084 if (!mode) {
3085 /* missing SP path LF */
3086 strbuf_reset(&line);
3087 strbuf_addstr(&line, "missing ");
3088 quote_c_style(path, &line, NULL, 0);
3089 strbuf_addch(&line, '\n');
3090 } else {
3091 /* mode SP type SP object_name TAB path LF */
3092 strbuf_reset(&line);
3093 strbuf_addf(&line, "%06o %s %s\t",
3094 mode & ~NO_DELTA, type, sha1_to_hex(sha1));
3095 quote_c_style(path, &line, NULL, 0);
3096 strbuf_addch(&line, '\n');
3098 cat_blob_write(line.buf, line.len);
3101 static void parse_ls(const char *p, struct branch *b)
3103 struct tree_entry *root = NULL;
3104 struct tree_entry leaf = {NULL};
3106 /* ls SP (<tree-ish> SP)? <path> */
3107 if (*p == '"') {
3108 if (!b)
3109 die("Not in a commit: %s", command_buf.buf);
3110 root = &b->branch_tree;
3111 } else {
3112 struct object_entry *e = parse_treeish_dataref(&p);
3113 root = new_tree_entry();
3114 oidcpy(&root->versions[1].oid, &e->idx.oid);
3115 if (!is_null_oid(&root->versions[1].oid))
3116 root->versions[1].mode = S_IFDIR;
3117 load_tree(root);
3119 if (*p == '"') {
3120 static struct strbuf uq = STRBUF_INIT;
3121 const char *endp;
3122 strbuf_reset(&uq);
3123 if (unquote_c_style(&uq, p, &endp))
3124 die("Invalid path: %s", command_buf.buf);
3125 if (*endp)
3126 die("Garbage after path in: %s", command_buf.buf);
3127 p = uq.buf;
3129 tree_content_get(root, p, &leaf, 1);
3131 * A directory in preparation would have a sha1 of zero
3132 * until it is saved. Save, for simplicity.
3134 if (S_ISDIR(leaf.versions[1].mode))
3135 store_tree(&leaf);
3137 print_ls(leaf.versions[1].mode, leaf.versions[1].oid.hash, p);
3138 if (leaf.tree)
3139 release_tree_content_recursive(leaf.tree);
3140 if (!b || root != &b->branch_tree)
3141 release_tree_entry(root);
3144 static void checkpoint(void)
3146 checkpoint_requested = 0;
3147 if (object_count) {
3148 cycle_packfile();
3150 dump_branches();
3151 dump_tags();
3152 dump_marks();
3155 static void parse_checkpoint(void)
3157 checkpoint_requested = 1;
3158 skip_optional_lf();
3161 static void parse_progress(void)
3163 fwrite(command_buf.buf, 1, command_buf.len, stdout);
3164 fputc('\n', stdout);
3165 fflush(stdout);
3166 skip_optional_lf();
3169 static char* make_fast_import_path(const char *path)
3171 if (!relative_marks_paths || is_absolute_path(path))
3172 return xstrdup(path);
3173 return git_pathdup("info/fast-import/%s", path);
3176 static void option_import_marks(const char *marks,
3177 int from_stream, int ignore_missing)
3179 if (import_marks_file) {
3180 if (from_stream)
3181 die("Only one import-marks command allowed per stream");
3183 /* read previous mark file */
3184 if(!import_marks_file_from_stream)
3185 read_marks();
3188 import_marks_file = make_fast_import_path(marks);
3189 safe_create_leading_directories_const(import_marks_file);
3190 import_marks_file_from_stream = from_stream;
3191 import_marks_file_ignore_missing = ignore_missing;
3194 static void option_date_format(const char *fmt)
3196 if (!strcmp(fmt, "raw"))
3197 whenspec = WHENSPEC_RAW;
3198 else if (!strcmp(fmt, "rfc2822"))
3199 whenspec = WHENSPEC_RFC2822;
3200 else if (!strcmp(fmt, "now"))
3201 whenspec = WHENSPEC_NOW;
3202 else
3203 die("unknown --date-format argument %s", fmt);
3206 static unsigned long ulong_arg(const char *option, const char *arg)
3208 char *endptr;
3209 unsigned long rv = strtoul(arg, &endptr, 0);
3210 if (strchr(arg, '-') || endptr == arg || *endptr)
3211 die("%s: argument must be a non-negative integer", option);
3212 return rv;
3215 static void option_depth(const char *depth)
3217 max_depth = ulong_arg("--depth", depth);
3218 if (max_depth > MAX_DEPTH)
3219 die("--depth cannot exceed %u", MAX_DEPTH);
3222 static void option_active_branches(const char *branches)
3224 max_active_branches = ulong_arg("--active-branches", branches);
3227 static void option_export_marks(const char *marks)
3229 export_marks_file = make_fast_import_path(marks);
3230 safe_create_leading_directories_const(export_marks_file);
3233 static void option_cat_blob_fd(const char *fd)
3235 unsigned long n = ulong_arg("--cat-blob-fd", fd);
3236 if (n > (unsigned long) INT_MAX)
3237 die("--cat-blob-fd cannot exceed %d", INT_MAX);
3238 cat_blob_fd = (int) n;
3241 static void option_export_pack_edges(const char *edges)
3243 if (pack_edges)
3244 fclose(pack_edges);
3245 pack_edges = xfopen(edges, "a");
3248 static int parse_one_option(const char *option)
3250 if (skip_prefix(option, "max-pack-size=", &option)) {
3251 unsigned long v;
3252 if (!git_parse_ulong(option, &v))
3253 return 0;
3254 if (v < 8192) {
3255 warning("max-pack-size is now in bytes, assuming --max-pack-size=%lum", v);
3256 v *= 1024 * 1024;
3257 } else if (v < 1024 * 1024) {
3258 warning("minimum max-pack-size is 1 MiB");
3259 v = 1024 * 1024;
3261 max_packsize = v;
3262 } else if (skip_prefix(option, "big-file-threshold=", &option)) {
3263 unsigned long v;
3264 if (!git_parse_ulong(option, &v))
3265 return 0;
3266 big_file_threshold = v;
3267 } else if (skip_prefix(option, "depth=", &option)) {
3268 option_depth(option);
3269 } else if (skip_prefix(option, "active-branches=", &option)) {
3270 option_active_branches(option);
3271 } else if (skip_prefix(option, "export-pack-edges=", &option)) {
3272 option_export_pack_edges(option);
3273 } else if (starts_with(option, "quiet")) {
3274 show_stats = 0;
3275 } else if (starts_with(option, "stats")) {
3276 show_stats = 1;
3277 } else {
3278 return 0;
3281 return 1;
3284 static int parse_one_feature(const char *feature, int from_stream)
3286 const char *arg;
3288 if (skip_prefix(feature, "date-format=", &arg)) {
3289 option_date_format(arg);
3290 } else if (skip_prefix(feature, "import-marks=", &arg)) {
3291 option_import_marks(arg, from_stream, 0);
3292 } else if (skip_prefix(feature, "import-marks-if-exists=", &arg)) {
3293 option_import_marks(arg, from_stream, 1);
3294 } else if (skip_prefix(feature, "export-marks=", &arg)) {
3295 option_export_marks(arg);
3296 } else if (!strcmp(feature, "get-mark")) {
3297 ; /* Don't die - this feature is supported */
3298 } else if (!strcmp(feature, "cat-blob")) {
3299 ; /* Don't die - this feature is supported */
3300 } else if (!strcmp(feature, "relative-marks")) {
3301 relative_marks_paths = 1;
3302 } else if (!strcmp(feature, "no-relative-marks")) {
3303 relative_marks_paths = 0;
3304 } else if (!strcmp(feature, "done")) {
3305 require_explicit_termination = 1;
3306 } else if (!strcmp(feature, "force")) {
3307 force_update = 1;
3308 } else if (!strcmp(feature, "notes") || !strcmp(feature, "ls")) {
3309 ; /* do nothing; we have the feature */
3310 } else {
3311 return 0;
3314 return 1;
3317 static void parse_feature(const char *feature)
3319 if (seen_data_command)
3320 die("Got feature command '%s' after data command", feature);
3322 if (parse_one_feature(feature, 1))
3323 return;
3325 die("This version of fast-import does not support feature %s.", feature);
3328 static void parse_option(const char *option)
3330 if (seen_data_command)
3331 die("Got option command '%s' after data command", option);
3333 if (parse_one_option(option))
3334 return;
3336 die("This version of fast-import does not support option: %s", option);
3339 static void git_pack_config(void)
3341 int indexversion_value;
3342 int limit;
3343 unsigned long packsizelimit_value;
3345 if (!git_config_get_ulong("pack.depth", &max_depth)) {
3346 if (max_depth > MAX_DEPTH)
3347 max_depth = MAX_DEPTH;
3349 if (!git_config_get_int("pack.indexversion", &indexversion_value)) {
3350 pack_idx_opts.version = indexversion_value;
3351 if (pack_idx_opts.version > 2)
3352 git_die_config("pack.indexversion",
3353 "bad pack.indexversion=%"PRIu32, pack_idx_opts.version);
3355 if (!git_config_get_ulong("pack.packsizelimit", &packsizelimit_value))
3356 max_packsize = packsizelimit_value;
3358 if (!git_config_get_int("fastimport.unpacklimit", &limit))
3359 unpack_limit = limit;
3360 else if (!git_config_get_int("transfer.unpacklimit", &limit))
3361 unpack_limit = limit;
3363 git_config(git_default_config, NULL);
3366 static const char fast_import_usage[] =
3367 "git fast-import [--date-format=<f>] [--max-pack-size=<n>] [--big-file-threshold=<n>] [--depth=<n>] [--active-branches=<n>] [--export-marks=<marks.file>]";
3369 static void parse_argv(void)
3371 unsigned int i;
3373 for (i = 1; i < global_argc; i++) {
3374 const char *a = global_argv[i];
3376 if (*a != '-' || !strcmp(a, "--"))
3377 break;
3379 if (!skip_prefix(a, "--", &a))
3380 die("unknown option %s", a);
3382 if (parse_one_option(a))
3383 continue;
3385 if (parse_one_feature(a, 0))
3386 continue;
3388 if (skip_prefix(a, "cat-blob-fd=", &a)) {
3389 option_cat_blob_fd(a);
3390 continue;
3393 die("unknown option --%s", a);
3395 if (i != global_argc)
3396 usage(fast_import_usage);
3398 seen_data_command = 1;
3399 if (import_marks_file)
3400 read_marks();
3403 int cmd_main(int argc, const char **argv)
3405 unsigned int i;
3407 if (argc == 2 && !strcmp(argv[1], "-h"))
3408 usage(fast_import_usage);
3410 setup_git_directory();
3411 reset_pack_idx_option(&pack_idx_opts);
3412 git_pack_config();
3414 alloc_objects(object_entry_alloc);
3415 strbuf_init(&command_buf, 0);
3416 atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
3417 branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
3418 avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
3419 marks = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
3421 global_argc = argc;
3422 global_argv = argv;
3424 rc_free = mem_pool_alloc(&fi_mem_pool, cmd_save * sizeof(*rc_free));
3425 for (i = 0; i < (cmd_save - 1); i++)
3426 rc_free[i].next = &rc_free[i + 1];
3427 rc_free[cmd_save - 1].next = NULL;
3429 prepare_packed_git();
3430 start_packfile();
3431 set_die_routine(die_nicely);
3432 set_checkpoint_signal();
3433 while (read_next_command() != EOF) {
3434 const char *v;
3435 if (!strcmp("blob", command_buf.buf))
3436 parse_new_blob();
3437 else if (skip_prefix(command_buf.buf, "ls ", &v))
3438 parse_ls(v, NULL);
3439 else if (skip_prefix(command_buf.buf, "commit ", &v))
3440 parse_new_commit(v);
3441 else if (skip_prefix(command_buf.buf, "tag ", &v))
3442 parse_new_tag(v);
3443 else if (skip_prefix(command_buf.buf, "reset ", &v))
3444 parse_reset_branch(v);
3445 else if (!strcmp("checkpoint", command_buf.buf))
3446 parse_checkpoint();
3447 else if (!strcmp("done", command_buf.buf))
3448 break;
3449 else if (starts_with(command_buf.buf, "progress "))
3450 parse_progress();
3451 else if (skip_prefix(command_buf.buf, "feature ", &v))
3452 parse_feature(v);
3453 else if (skip_prefix(command_buf.buf, "option git ", &v))
3454 parse_option(v);
3455 else if (starts_with(command_buf.buf, "option "))
3456 /* ignore non-git options*/;
3457 else
3458 die("Unsupported command: %s", command_buf.buf);
3460 if (checkpoint_requested)
3461 checkpoint();
3464 /* argv hasn't been parsed yet, do so */
3465 if (!seen_data_command)
3466 parse_argv();
3468 if (require_explicit_termination && feof(stdin))
3469 die("stream ends early");
3471 end_packfile();
3473 dump_branches();
3474 dump_tags();
3475 unkeep_all_packs();
3476 dump_marks();
3478 if (pack_edges)
3479 fclose(pack_edges);
3481 if (show_stats) {
3482 uintmax_t total_count = 0, duplicate_count = 0;
3483 for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
3484 total_count += object_count_by_type[i];
3485 for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
3486 duplicate_count += duplicate_count_by_type[i];
3488 fprintf(stderr, "%s statistics:\n", argv[0]);
3489 fprintf(stderr, "---------------------------------------------------------------------\n");
3490 fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
3491 fprintf(stderr, "Total objects: %10" PRIuMAX " (%10" PRIuMAX " duplicates )\n", total_count, duplicate_count);
3492 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]);
3493 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]);
3494 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]);
3495 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]);
3496 fprintf(stderr, "Total branches: %10lu (%10lu loads )\n", branch_count, branch_load_count);
3497 fprintf(stderr, " marks: %10" PRIuMAX " (%10" PRIuMAX " unique )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
3498 fprintf(stderr, " atoms: %10u\n", atom_cnt);
3499 fprintf(stderr, "Memory total: %10" PRIuMAX " KiB\n", (tree_entry_allocd + fi_mem_pool.pool_alloc + alloc_count*sizeof(struct object_entry))/1024);
3500 fprintf(stderr, " pools: %10lu KiB\n", (unsigned long)((tree_entry_allocd + fi_mem_pool.pool_alloc) /1024));
3501 fprintf(stderr, " objects: %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
3502 fprintf(stderr, "---------------------------------------------------------------------\n");
3503 pack_report();
3504 fprintf(stderr, "---------------------------------------------------------------------\n");
3505 fprintf(stderr, "\n");
3508 return failure ? 1 : 0;