Merge branch 'ab/remove-implicit-use-of-the-repository' into en/header-split-cache-h
[git/debian.git] / builtin / fast-import.c
blob68b1a539870c3a27cd70fd662a9bf82b1fdef698
1 #include "builtin.h"
2 #include "abspath.h"
3 #include "cache.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "repository.h"
8 #include "config.h"
9 #include "lockfile.h"
10 #include "object.h"
11 #include "blob.h"
12 #include "tree.h"
13 #include "commit.h"
14 #include "delta.h"
15 #include "pack.h"
16 #include "refs.h"
17 #include "csum-file.h"
18 #include "quote.h"
19 #include "dir.h"
20 #include "run-command.h"
21 #include "packfile.h"
22 #include "object-store.h"
23 #include "mem-pool.h"
24 #include "commit-reach.h"
25 #include "khash.h"
26 #include "date.h"
27 #include "wrapper.h"
29 #define PACK_ID_BITS 16
30 #define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
31 #define DEPTH_BITS 13
32 #define MAX_DEPTH ((1<<DEPTH_BITS)-1)
35 * We abuse the setuid bit on directories to mean "do not delta".
37 #define NO_DELTA S_ISUID
40 * The amount of additional space required in order to write an object into the
41 * current pack. This is the hash lengths at the end of the pack, plus the
42 * length of one object ID.
44 #define PACK_SIZE_THRESHOLD (the_hash_algo->rawsz * 3)
46 struct object_entry {
47 struct pack_idx_entry idx;
48 struct hashmap_entry ent;
49 uint32_t type : TYPE_BITS,
50 pack_id : PACK_ID_BITS,
51 depth : DEPTH_BITS;
54 static int object_entry_hashcmp(const void *map_data UNUSED,
55 const struct hashmap_entry *eptr,
56 const struct hashmap_entry *entry_or_key,
57 const void *keydata)
59 const struct object_id *oid = keydata;
60 const struct object_entry *e1, *e2;
62 e1 = container_of(eptr, const struct object_entry, ent);
63 if (oid)
64 return oidcmp(&e1->idx.oid, oid);
66 e2 = container_of(entry_or_key, const struct object_entry, ent);
67 return oidcmp(&e1->idx.oid, &e2->idx.oid);
70 struct object_entry_pool {
71 struct object_entry_pool *next_pool;
72 struct object_entry *next_free;
73 struct object_entry *end;
74 struct object_entry entries[FLEX_ARRAY]; /* more */
77 struct mark_set {
78 union {
79 struct object_id *oids[1024];
80 struct object_entry *marked[1024];
81 struct mark_set *sets[1024];
82 } data;
83 unsigned int shift;
86 struct last_object {
87 struct strbuf data;
88 off_t offset;
89 unsigned int depth;
90 unsigned no_swap : 1;
93 struct atom_str {
94 struct atom_str *next_atom;
95 unsigned short str_len;
96 char str_dat[FLEX_ARRAY]; /* more */
99 struct tree_content;
100 struct tree_entry {
101 struct tree_content *tree;
102 struct atom_str *name;
103 struct tree_entry_ms {
104 uint16_t mode;
105 struct object_id oid;
106 } versions[2];
109 struct tree_content {
110 unsigned int entry_capacity; /* must match avail_tree_content */
111 unsigned int entry_count;
112 unsigned int delta_depth;
113 struct tree_entry *entries[FLEX_ARRAY]; /* more */
116 struct avail_tree_content {
117 unsigned int entry_capacity; /* must match tree_content */
118 struct avail_tree_content *next_avail;
121 struct branch {
122 struct branch *table_next_branch;
123 struct branch *active_next_branch;
124 const char *name;
125 struct tree_entry branch_tree;
126 uintmax_t last_commit;
127 uintmax_t num_notes;
128 unsigned active : 1;
129 unsigned delete : 1;
130 unsigned pack_id : PACK_ID_BITS;
131 struct object_id oid;
134 struct tag {
135 struct tag *next_tag;
136 const char *name;
137 unsigned int pack_id;
138 struct object_id oid;
141 struct hash_list {
142 struct hash_list *next;
143 struct object_id oid;
146 typedef enum {
147 WHENSPEC_RAW = 1,
148 WHENSPEC_RAW_PERMISSIVE,
149 WHENSPEC_RFC2822,
150 WHENSPEC_NOW
151 } whenspec_type;
153 struct recent_command {
154 struct recent_command *prev;
155 struct recent_command *next;
156 char *buf;
159 typedef void (*mark_set_inserter_t)(struct mark_set **s, struct object_id *oid, uintmax_t mark);
160 typedef void (*each_mark_fn_t)(uintmax_t mark, void *obj, void *cbp);
162 /* Configured limits on output */
163 static unsigned long max_depth = 50;
164 static off_t max_packsize;
165 static int unpack_limit = 100;
166 static int force_update;
168 /* Stats and misc. counters */
169 static uintmax_t alloc_count;
170 static uintmax_t marks_set_count;
171 static uintmax_t object_count_by_type[1 << TYPE_BITS];
172 static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
173 static uintmax_t delta_count_by_type[1 << TYPE_BITS];
174 static uintmax_t delta_count_attempts_by_type[1 << TYPE_BITS];
175 static unsigned long object_count;
176 static unsigned long branch_count;
177 static unsigned long branch_load_count;
178 static int failure;
179 static FILE *pack_edges;
180 static unsigned int show_stats = 1;
181 static int global_argc;
182 static const char **global_argv;
184 /* Memory pools */
185 static struct mem_pool fi_mem_pool = {
186 .block_alloc = 2*1024*1024 - sizeof(struct mp_block),
189 /* Atom management */
190 static unsigned int atom_table_sz = 4451;
191 static unsigned int atom_cnt;
192 static struct atom_str **atom_table;
194 /* The .pack file being generated */
195 static struct pack_idx_option pack_idx_opts;
196 static unsigned int pack_id;
197 static struct hashfile *pack_file;
198 static struct packed_git *pack_data;
199 static struct packed_git **all_packs;
200 static off_t pack_size;
202 /* Table of objects we've written. */
203 static unsigned int object_entry_alloc = 5000;
204 static struct object_entry_pool *blocks;
205 static struct hashmap object_table;
206 static struct mark_set *marks;
207 static const char *export_marks_file;
208 static const char *import_marks_file;
209 static int import_marks_file_from_stream;
210 static int import_marks_file_ignore_missing;
211 static int import_marks_file_done;
212 static int relative_marks_paths;
214 /* Our last blob */
215 static struct last_object last_blob = {
216 .data = STRBUF_INIT,
219 /* Tree management */
220 static unsigned int tree_entry_alloc = 1000;
221 static void *avail_tree_entry;
222 static unsigned int avail_tree_table_sz = 100;
223 static struct avail_tree_content **avail_tree_table;
224 static size_t tree_entry_allocd;
225 static struct strbuf old_tree = STRBUF_INIT;
226 static struct strbuf new_tree = STRBUF_INIT;
228 /* Branch data */
229 static unsigned long max_active_branches = 5;
230 static unsigned long cur_active_branches;
231 static unsigned long branch_table_sz = 1039;
232 static struct branch **branch_table;
233 static struct branch *active_branches;
235 /* Tag data */
236 static struct tag *first_tag;
237 static struct tag *last_tag;
239 /* Input stream parsing */
240 static whenspec_type whenspec = WHENSPEC_RAW;
241 static struct strbuf command_buf = STRBUF_INIT;
242 static int unread_command_buf;
243 static struct recent_command cmd_hist = {
244 .prev = &cmd_hist,
245 .next = &cmd_hist,
247 static struct recent_command *cmd_tail = &cmd_hist;
248 static struct recent_command *rc_free;
249 static unsigned int cmd_save = 100;
250 static uintmax_t next_mark;
251 static struct strbuf new_data = STRBUF_INIT;
252 static int seen_data_command;
253 static int require_explicit_termination;
254 static int allow_unsafe_features;
256 /* Signal handling */
257 static volatile sig_atomic_t checkpoint_requested;
259 /* Submodule marks */
260 static struct string_list sub_marks_from = STRING_LIST_INIT_DUP;
261 static struct string_list sub_marks_to = STRING_LIST_INIT_DUP;
262 static kh_oid_map_t *sub_oid_map;
264 /* Where to write output of cat-blob commands */
265 static int cat_blob_fd = STDOUT_FILENO;
267 static void parse_argv(void);
268 static void parse_get_mark(const char *p);
269 static void parse_cat_blob(const char *p);
270 static void parse_ls(const char *p, struct branch *b);
272 static void for_each_mark(struct mark_set *m, uintmax_t base, each_mark_fn_t callback, void *p)
274 uintmax_t k;
275 if (m->shift) {
276 for (k = 0; k < 1024; k++) {
277 if (m->data.sets[k])
278 for_each_mark(m->data.sets[k], base + (k << m->shift), callback, p);
280 } else {
281 for (k = 0; k < 1024; k++) {
282 if (m->data.marked[k])
283 callback(base + k, m->data.marked[k], p);
288 static void dump_marks_fn(uintmax_t mark, void *object, void *cbp) {
289 struct object_entry *e = object;
290 FILE *f = cbp;
292 fprintf(f, ":%" PRIuMAX " %s\n", mark, oid_to_hex(&e->idx.oid));
295 static void write_branch_report(FILE *rpt, struct branch *b)
297 fprintf(rpt, "%s:\n", b->name);
299 fprintf(rpt, " status :");
300 if (b->active)
301 fputs(" active", rpt);
302 if (b->branch_tree.tree)
303 fputs(" loaded", rpt);
304 if (is_null_oid(&b->branch_tree.versions[1].oid))
305 fputs(" dirty", rpt);
306 fputc('\n', rpt);
308 fprintf(rpt, " tip commit : %s\n", oid_to_hex(&b->oid));
309 fprintf(rpt, " old tree : %s\n",
310 oid_to_hex(&b->branch_tree.versions[0].oid));
311 fprintf(rpt, " cur tree : %s\n",
312 oid_to_hex(&b->branch_tree.versions[1].oid));
313 fprintf(rpt, " commit clock: %" PRIuMAX "\n", b->last_commit);
315 fputs(" last pack : ", rpt);
316 if (b->pack_id < MAX_PACK_ID)
317 fprintf(rpt, "%u", b->pack_id);
318 fputc('\n', rpt);
320 fputc('\n', rpt);
323 static void write_crash_report(const char *err)
325 char *loc = git_pathdup("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
326 FILE *rpt = fopen(loc, "w");
327 struct branch *b;
328 unsigned long lu;
329 struct recent_command *rc;
331 if (!rpt) {
332 error_errno("can't write crash report %s", loc);
333 free(loc);
334 return;
337 fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
339 fprintf(rpt, "fast-import crash report:\n");
340 fprintf(rpt, " fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
341 fprintf(rpt, " parent process : %"PRIuMAX"\n", (uintmax_t) getppid());
342 fprintf(rpt, " at %s\n", show_date(time(NULL), 0, DATE_MODE(ISO8601)));
343 fputc('\n', rpt);
345 fputs("fatal: ", rpt);
346 fputs(err, rpt);
347 fputc('\n', rpt);
349 fputc('\n', rpt);
350 fputs("Most Recent Commands Before Crash\n", rpt);
351 fputs("---------------------------------\n", rpt);
352 for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
353 if (rc->next == &cmd_hist)
354 fputs("* ", rpt);
355 else
356 fputs(" ", rpt);
357 fputs(rc->buf, rpt);
358 fputc('\n', rpt);
361 fputc('\n', rpt);
362 fputs("Active Branch LRU\n", rpt);
363 fputs("-----------------\n", rpt);
364 fprintf(rpt, " active_branches = %lu cur, %lu max\n",
365 cur_active_branches,
366 max_active_branches);
367 fputc('\n', rpt);
368 fputs(" pos clock name\n", rpt);
369 fputs(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
370 for (b = active_branches, lu = 0; b; b = b->active_next_branch)
371 fprintf(rpt, " %2lu) %6" PRIuMAX" %s\n",
372 ++lu, b->last_commit, b->name);
374 fputc('\n', rpt);
375 fputs("Inactive Branches\n", rpt);
376 fputs("-----------------\n", rpt);
377 for (lu = 0; lu < branch_table_sz; lu++) {
378 for (b = branch_table[lu]; b; b = b->table_next_branch)
379 write_branch_report(rpt, b);
382 if (first_tag) {
383 struct tag *tg;
384 fputc('\n', rpt);
385 fputs("Annotated Tags\n", rpt);
386 fputs("--------------\n", rpt);
387 for (tg = first_tag; tg; tg = tg->next_tag) {
388 fputs(oid_to_hex(&tg->oid), rpt);
389 fputc(' ', rpt);
390 fputs(tg->name, rpt);
391 fputc('\n', rpt);
395 fputc('\n', rpt);
396 fputs("Marks\n", rpt);
397 fputs("-----\n", rpt);
398 if (export_marks_file)
399 fprintf(rpt, " exported to %s\n", export_marks_file);
400 else
401 for_each_mark(marks, 0, dump_marks_fn, rpt);
403 fputc('\n', rpt);
404 fputs("-------------------\n", rpt);
405 fputs("END OF CRASH REPORT\n", rpt);
406 fclose(rpt);
407 free(loc);
410 static void end_packfile(void);
411 static void unkeep_all_packs(void);
412 static void dump_marks(void);
414 static NORETURN void die_nicely(const char *err, va_list params)
416 va_list cp;
417 static int zombie;
418 report_fn die_message_fn = get_die_message_routine();
420 va_copy(cp, params);
421 die_message_fn(err, params);
423 if (!zombie) {
424 char message[2 * PATH_MAX];
426 zombie = 1;
427 vsnprintf(message, sizeof(message), err, cp);
428 write_crash_report(message);
429 end_packfile();
430 unkeep_all_packs();
431 dump_marks();
433 exit(128);
436 #ifndef SIGUSR1 /* Windows, for example */
438 static void set_checkpoint_signal(void)
442 #else
444 static void checkpoint_signal(int signo UNUSED)
446 checkpoint_requested = 1;
449 static void set_checkpoint_signal(void)
451 struct sigaction sa;
453 memset(&sa, 0, sizeof(sa));
454 sa.sa_handler = checkpoint_signal;
455 sigemptyset(&sa.sa_mask);
456 sa.sa_flags = SA_RESTART;
457 sigaction(SIGUSR1, &sa, NULL);
460 #endif
462 static void alloc_objects(unsigned int cnt)
464 struct object_entry_pool *b;
466 b = xmalloc(sizeof(struct object_entry_pool)
467 + cnt * sizeof(struct object_entry));
468 b->next_pool = blocks;
469 b->next_free = b->entries;
470 b->end = b->entries + cnt;
471 blocks = b;
472 alloc_count += cnt;
475 static struct object_entry *new_object(struct object_id *oid)
477 struct object_entry *e;
479 if (blocks->next_free == blocks->end)
480 alloc_objects(object_entry_alloc);
482 e = blocks->next_free++;
483 oidcpy(&e->idx.oid, oid);
484 return e;
487 static struct object_entry *find_object(struct object_id *oid)
489 return hashmap_get_entry_from_hash(&object_table, oidhash(oid), oid,
490 struct object_entry, ent);
493 static struct object_entry *insert_object(struct object_id *oid)
495 struct object_entry *e;
496 unsigned int hash = oidhash(oid);
498 e = hashmap_get_entry_from_hash(&object_table, hash, oid,
499 struct object_entry, ent);
500 if (!e) {
501 e = new_object(oid);
502 e->idx.offset = 0;
503 hashmap_entry_init(&e->ent, hash);
504 hashmap_add(&object_table, &e->ent);
507 return e;
510 static void invalidate_pack_id(unsigned int id)
512 unsigned long lu;
513 struct tag *t;
514 struct hashmap_iter iter;
515 struct object_entry *e;
517 hashmap_for_each_entry(&object_table, &iter, e, ent) {
518 if (e->pack_id == id)
519 e->pack_id = MAX_PACK_ID;
522 for (lu = 0; lu < branch_table_sz; lu++) {
523 struct branch *b;
525 for (b = branch_table[lu]; b; b = b->table_next_branch)
526 if (b->pack_id == id)
527 b->pack_id = MAX_PACK_ID;
530 for (t = first_tag; t; t = t->next_tag)
531 if (t->pack_id == id)
532 t->pack_id = MAX_PACK_ID;
535 static unsigned int hc_str(const char *s, size_t len)
537 unsigned int r = 0;
538 while (len-- > 0)
539 r = r * 31 + *s++;
540 return r;
543 static void insert_mark(struct mark_set **top, uintmax_t idnum, struct object_entry *oe)
545 struct mark_set *s = *top;
547 while ((idnum >> s->shift) >= 1024) {
548 s = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
549 s->shift = (*top)->shift + 10;
550 s->data.sets[0] = *top;
551 *top = s;
553 while (s->shift) {
554 uintmax_t i = idnum >> s->shift;
555 idnum -= i << s->shift;
556 if (!s->data.sets[i]) {
557 s->data.sets[i] = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
558 s->data.sets[i]->shift = s->shift - 10;
560 s = s->data.sets[i];
562 if (!s->data.marked[idnum])
563 marks_set_count++;
564 s->data.marked[idnum] = oe;
567 static void *find_mark(struct mark_set *s, uintmax_t idnum)
569 uintmax_t orig_idnum = idnum;
570 struct object_entry *oe = NULL;
571 if ((idnum >> s->shift) < 1024) {
572 while (s && s->shift) {
573 uintmax_t i = idnum >> s->shift;
574 idnum -= i << s->shift;
575 s = s->data.sets[i];
577 if (s)
578 oe = s->data.marked[idnum];
580 if (!oe)
581 die("mark :%" PRIuMAX " not declared", orig_idnum);
582 return oe;
585 static struct atom_str *to_atom(const char *s, unsigned short len)
587 unsigned int hc = hc_str(s, len) % atom_table_sz;
588 struct atom_str *c;
590 for (c = atom_table[hc]; c; c = c->next_atom)
591 if (c->str_len == len && !strncmp(s, c->str_dat, len))
592 return c;
594 c = mem_pool_alloc(&fi_mem_pool, sizeof(struct atom_str) + len + 1);
595 c->str_len = len;
596 memcpy(c->str_dat, s, len);
597 c->str_dat[len] = 0;
598 c->next_atom = atom_table[hc];
599 atom_table[hc] = c;
600 atom_cnt++;
601 return c;
604 static struct branch *lookup_branch(const char *name)
606 unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
607 struct branch *b;
609 for (b = branch_table[hc]; b; b = b->table_next_branch)
610 if (!strcmp(name, b->name))
611 return b;
612 return NULL;
615 static struct branch *new_branch(const char *name)
617 unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
618 struct branch *b = lookup_branch(name);
620 if (b)
621 die("Invalid attempt to create duplicate branch: %s", name);
622 if (check_refname_format(name, REFNAME_ALLOW_ONELEVEL))
623 die("Branch name doesn't conform to GIT standards: %s", name);
625 b = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct branch));
626 b->name = mem_pool_strdup(&fi_mem_pool, name);
627 b->table_next_branch = branch_table[hc];
628 b->branch_tree.versions[0].mode = S_IFDIR;
629 b->branch_tree.versions[1].mode = S_IFDIR;
630 b->num_notes = 0;
631 b->active = 0;
632 b->pack_id = MAX_PACK_ID;
633 branch_table[hc] = b;
634 branch_count++;
635 return b;
638 static unsigned int hc_entries(unsigned int cnt)
640 cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
641 return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
644 static struct tree_content *new_tree_content(unsigned int cnt)
646 struct avail_tree_content *f, *l = NULL;
647 struct tree_content *t;
648 unsigned int hc = hc_entries(cnt);
650 for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
651 if (f->entry_capacity >= cnt)
652 break;
654 if (f) {
655 if (l)
656 l->next_avail = f->next_avail;
657 else
658 avail_tree_table[hc] = f->next_avail;
659 } else {
660 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
661 f = mem_pool_alloc(&fi_mem_pool, sizeof(*t) + sizeof(t->entries[0]) * cnt);
662 f->entry_capacity = cnt;
665 t = (struct tree_content*)f;
666 t->entry_count = 0;
667 t->delta_depth = 0;
668 return t;
671 static void release_tree_entry(struct tree_entry *e);
672 static void release_tree_content(struct tree_content *t)
674 struct avail_tree_content *f = (struct avail_tree_content*)t;
675 unsigned int hc = hc_entries(f->entry_capacity);
676 f->next_avail = avail_tree_table[hc];
677 avail_tree_table[hc] = f;
680 static void release_tree_content_recursive(struct tree_content *t)
682 unsigned int i;
683 for (i = 0; i < t->entry_count; i++)
684 release_tree_entry(t->entries[i]);
685 release_tree_content(t);
688 static struct tree_content *grow_tree_content(
689 struct tree_content *t,
690 int amt)
692 struct tree_content *r = new_tree_content(t->entry_count + amt);
693 r->entry_count = t->entry_count;
694 r->delta_depth = t->delta_depth;
695 COPY_ARRAY(r->entries, t->entries, t->entry_count);
696 release_tree_content(t);
697 return r;
700 static struct tree_entry *new_tree_entry(void)
702 struct tree_entry *e;
704 if (!avail_tree_entry) {
705 unsigned int n = tree_entry_alloc;
706 tree_entry_allocd += n * sizeof(struct tree_entry);
707 ALLOC_ARRAY(e, n);
708 avail_tree_entry = e;
709 while (n-- > 1) {
710 *((void**)e) = e + 1;
711 e++;
713 *((void**)e) = NULL;
716 e = avail_tree_entry;
717 avail_tree_entry = *((void**)e);
718 return e;
721 static void release_tree_entry(struct tree_entry *e)
723 if (e->tree)
724 release_tree_content_recursive(e->tree);
725 *((void**)e) = avail_tree_entry;
726 avail_tree_entry = e;
729 static struct tree_content *dup_tree_content(struct tree_content *s)
731 struct tree_content *d;
732 struct tree_entry *a, *b;
733 unsigned int i;
735 if (!s)
736 return NULL;
737 d = new_tree_content(s->entry_count);
738 for (i = 0; i < s->entry_count; i++) {
739 a = s->entries[i];
740 b = new_tree_entry();
741 memcpy(b, a, sizeof(*a));
742 if (a->tree && is_null_oid(&b->versions[1].oid))
743 b->tree = dup_tree_content(a->tree);
744 else
745 b->tree = NULL;
746 d->entries[i] = b;
748 d->entry_count = s->entry_count;
749 d->delta_depth = s->delta_depth;
751 return d;
754 static void start_packfile(void)
756 struct strbuf tmp_file = STRBUF_INIT;
757 struct packed_git *p;
758 int pack_fd;
760 pack_fd = odb_mkstemp(&tmp_file, "pack/tmp_pack_XXXXXX");
761 FLEX_ALLOC_STR(p, pack_name, tmp_file.buf);
762 strbuf_release(&tmp_file);
764 p->pack_fd = pack_fd;
765 p->do_not_close = 1;
766 pack_file = hashfd(pack_fd, p->pack_name);
768 pack_data = p;
769 pack_size = write_pack_header(pack_file, 0);
770 object_count = 0;
772 REALLOC_ARRAY(all_packs, pack_id + 1);
773 all_packs[pack_id] = p;
776 static const char *create_index(void)
778 const char *tmpfile;
779 struct pack_idx_entry **idx, **c, **last;
780 struct object_entry *e;
781 struct object_entry_pool *o;
783 /* Build the table of object IDs. */
784 ALLOC_ARRAY(idx, object_count);
785 c = idx;
786 for (o = blocks; o; o = o->next_pool)
787 for (e = o->next_free; e-- != o->entries;)
788 if (pack_id == e->pack_id)
789 *c++ = &e->idx;
790 last = idx + object_count;
791 if (c != last)
792 die("internal consistency error creating the index");
794 tmpfile = write_idx_file(NULL, idx, object_count, &pack_idx_opts,
795 pack_data->hash);
796 free(idx);
797 return tmpfile;
800 static char *keep_pack(const char *curr_index_name)
802 static const char *keep_msg = "fast-import";
803 struct strbuf name = STRBUF_INIT;
804 int keep_fd;
806 odb_pack_name(&name, pack_data->hash, "keep");
807 keep_fd = odb_pack_keep(name.buf);
808 if (keep_fd < 0)
809 die_errno("cannot create keep file");
810 write_or_die(keep_fd, keep_msg, strlen(keep_msg));
811 if (close(keep_fd))
812 die_errno("failed to write keep file");
814 odb_pack_name(&name, pack_data->hash, "pack");
815 if (finalize_object_file(pack_data->pack_name, name.buf))
816 die("cannot store pack file");
818 odb_pack_name(&name, pack_data->hash, "idx");
819 if (finalize_object_file(curr_index_name, name.buf))
820 die("cannot store index file");
821 free((void *)curr_index_name);
822 return strbuf_detach(&name, NULL);
825 static void unkeep_all_packs(void)
827 struct strbuf name = STRBUF_INIT;
828 int k;
830 for (k = 0; k < pack_id; k++) {
831 struct packed_git *p = all_packs[k];
832 odb_pack_name(&name, p->hash, "keep");
833 unlink_or_warn(name.buf);
835 strbuf_release(&name);
838 static int loosen_small_pack(const struct packed_git *p)
840 struct child_process unpack = CHILD_PROCESS_INIT;
842 if (lseek(p->pack_fd, 0, SEEK_SET) < 0)
843 die_errno("Failed seeking to start of '%s'", p->pack_name);
845 unpack.in = p->pack_fd;
846 unpack.git_cmd = 1;
847 unpack.stdout_to_stderr = 1;
848 strvec_push(&unpack.args, "unpack-objects");
849 if (!show_stats)
850 strvec_push(&unpack.args, "-q");
852 return run_command(&unpack);
855 static void end_packfile(void)
857 static int running;
859 if (running || !pack_data)
860 return;
862 running = 1;
863 clear_delta_base_cache();
864 if (object_count) {
865 struct packed_git *new_p;
866 struct object_id cur_pack_oid;
867 char *idx_name;
868 int i;
869 struct branch *b;
870 struct tag *t;
872 close_pack_windows(pack_data);
873 finalize_hashfile(pack_file, cur_pack_oid.hash, FSYNC_COMPONENT_PACK, 0);
874 fixup_pack_header_footer(pack_data->pack_fd, pack_data->hash,
875 pack_data->pack_name, object_count,
876 cur_pack_oid.hash, pack_size);
878 if (object_count <= unpack_limit) {
879 if (!loosen_small_pack(pack_data)) {
880 invalidate_pack_id(pack_id);
881 goto discard_pack;
885 close(pack_data->pack_fd);
886 idx_name = keep_pack(create_index());
888 /* Register the packfile with core git's machinery. */
889 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
890 if (!new_p)
891 die("core git rejected index %s", idx_name);
892 all_packs[pack_id] = new_p;
893 install_packed_git(the_repository, new_p);
894 free(idx_name);
896 /* Print the boundary */
897 if (pack_edges) {
898 fprintf(pack_edges, "%s:", new_p->pack_name);
899 for (i = 0; i < branch_table_sz; i++) {
900 for (b = branch_table[i]; b; b = b->table_next_branch) {
901 if (b->pack_id == pack_id)
902 fprintf(pack_edges, " %s",
903 oid_to_hex(&b->oid));
906 for (t = first_tag; t; t = t->next_tag) {
907 if (t->pack_id == pack_id)
908 fprintf(pack_edges, " %s",
909 oid_to_hex(&t->oid));
911 fputc('\n', pack_edges);
912 fflush(pack_edges);
915 pack_id++;
917 else {
918 discard_pack:
919 close(pack_data->pack_fd);
920 unlink_or_warn(pack_data->pack_name);
922 FREE_AND_NULL(pack_data);
923 running = 0;
925 /* We can't carry a delta across packfiles. */
926 strbuf_release(&last_blob.data);
927 last_blob.offset = 0;
928 last_blob.depth = 0;
931 static void cycle_packfile(void)
933 end_packfile();
934 start_packfile();
937 static int store_object(
938 enum object_type type,
939 struct strbuf *dat,
940 struct last_object *last,
941 struct object_id *oidout,
942 uintmax_t mark)
944 void *out, *delta;
945 struct object_entry *e;
946 unsigned char hdr[96];
947 struct object_id oid;
948 unsigned long hdrlen, deltalen;
949 git_hash_ctx c;
950 git_zstream s;
952 hdrlen = format_object_header((char *)hdr, sizeof(hdr), type,
953 dat->len);
954 the_hash_algo->init_fn(&c);
955 the_hash_algo->update_fn(&c, hdr, hdrlen);
956 the_hash_algo->update_fn(&c, dat->buf, dat->len);
957 the_hash_algo->final_oid_fn(&oid, &c);
958 if (oidout)
959 oidcpy(oidout, &oid);
961 e = insert_object(&oid);
962 if (mark)
963 insert_mark(&marks, mark, e);
964 if (e->idx.offset) {
965 duplicate_count_by_type[type]++;
966 return 1;
967 } else if (find_sha1_pack(oid.hash,
968 get_all_packs(the_repository))) {
969 e->type = type;
970 e->pack_id = MAX_PACK_ID;
971 e->idx.offset = 1; /* just not zero! */
972 duplicate_count_by_type[type]++;
973 return 1;
976 if (last && last->data.len && last->data.buf && last->depth < max_depth
977 && dat->len > the_hash_algo->rawsz) {
979 delta_count_attempts_by_type[type]++;
980 delta = diff_delta(last->data.buf, last->data.len,
981 dat->buf, dat->len,
982 &deltalen, dat->len - the_hash_algo->rawsz);
983 } else
984 delta = NULL;
986 git_deflate_init(&s, pack_compression_level);
987 if (delta) {
988 s.next_in = delta;
989 s.avail_in = deltalen;
990 } else {
991 s.next_in = (void *)dat->buf;
992 s.avail_in = dat->len;
994 s.avail_out = git_deflate_bound(&s, s.avail_in);
995 s.next_out = out = xmalloc(s.avail_out);
996 while (git_deflate(&s, Z_FINISH) == Z_OK)
997 ; /* nothing */
998 git_deflate_end(&s);
1000 /* Determine if we should auto-checkpoint. */
1001 if ((max_packsize
1002 && (pack_size + PACK_SIZE_THRESHOLD + s.total_out) > max_packsize)
1003 || (pack_size + PACK_SIZE_THRESHOLD + s.total_out) < pack_size) {
1005 /* This new object needs to *not* have the current pack_id. */
1006 e->pack_id = pack_id + 1;
1007 cycle_packfile();
1009 /* We cannot carry a delta into the new pack. */
1010 if (delta) {
1011 FREE_AND_NULL(delta);
1013 git_deflate_init(&s, pack_compression_level);
1014 s.next_in = (void *)dat->buf;
1015 s.avail_in = dat->len;
1016 s.avail_out = git_deflate_bound(&s, s.avail_in);
1017 s.next_out = out = xrealloc(out, s.avail_out);
1018 while (git_deflate(&s, Z_FINISH) == Z_OK)
1019 ; /* nothing */
1020 git_deflate_end(&s);
1024 e->type = type;
1025 e->pack_id = pack_id;
1026 e->idx.offset = pack_size;
1027 object_count++;
1028 object_count_by_type[type]++;
1030 crc32_begin(pack_file);
1032 if (delta) {
1033 off_t ofs = e->idx.offset - last->offset;
1034 unsigned pos = sizeof(hdr) - 1;
1036 delta_count_by_type[type]++;
1037 e->depth = last->depth + 1;
1039 hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1040 OBJ_OFS_DELTA, deltalen);
1041 hashwrite(pack_file, hdr, hdrlen);
1042 pack_size += hdrlen;
1044 hdr[pos] = ofs & 127;
1045 while (ofs >>= 7)
1046 hdr[--pos] = 128 | (--ofs & 127);
1047 hashwrite(pack_file, hdr + pos, sizeof(hdr) - pos);
1048 pack_size += sizeof(hdr) - pos;
1049 } else {
1050 e->depth = 0;
1051 hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1052 type, dat->len);
1053 hashwrite(pack_file, hdr, hdrlen);
1054 pack_size += hdrlen;
1057 hashwrite(pack_file, out, s.total_out);
1058 pack_size += s.total_out;
1060 e->idx.crc32 = crc32_end(pack_file);
1062 free(out);
1063 free(delta);
1064 if (last) {
1065 if (last->no_swap) {
1066 last->data = *dat;
1067 } else {
1068 strbuf_swap(&last->data, dat);
1070 last->offset = e->idx.offset;
1071 last->depth = e->depth;
1073 return 0;
1076 static void truncate_pack(struct hashfile_checkpoint *checkpoint)
1078 if (hashfile_truncate(pack_file, checkpoint))
1079 die_errno("cannot truncate pack to skip duplicate");
1080 pack_size = checkpoint->offset;
1083 static void stream_blob(uintmax_t len, struct object_id *oidout, uintmax_t mark)
1085 size_t in_sz = 64 * 1024, out_sz = 64 * 1024;
1086 unsigned char *in_buf = xmalloc(in_sz);
1087 unsigned char *out_buf = xmalloc(out_sz);
1088 struct object_entry *e;
1089 struct object_id oid;
1090 unsigned long hdrlen;
1091 off_t offset;
1092 git_hash_ctx c;
1093 git_zstream s;
1094 struct hashfile_checkpoint checkpoint;
1095 int status = Z_OK;
1097 /* Determine if we should auto-checkpoint. */
1098 if ((max_packsize
1099 && (pack_size + PACK_SIZE_THRESHOLD + len) > max_packsize)
1100 || (pack_size + PACK_SIZE_THRESHOLD + len) < pack_size)
1101 cycle_packfile();
1103 hashfile_checkpoint(pack_file, &checkpoint);
1104 offset = checkpoint.offset;
1106 hdrlen = format_object_header((char *)out_buf, out_sz, OBJ_BLOB, len);
1108 the_hash_algo->init_fn(&c);
1109 the_hash_algo->update_fn(&c, out_buf, hdrlen);
1111 crc32_begin(pack_file);
1113 git_deflate_init(&s, pack_compression_level);
1115 hdrlen = encode_in_pack_object_header(out_buf, out_sz, OBJ_BLOB, len);
1117 s.next_out = out_buf + hdrlen;
1118 s.avail_out = out_sz - hdrlen;
1120 while (status != Z_STREAM_END) {
1121 if (0 < len && !s.avail_in) {
1122 size_t cnt = in_sz < len ? in_sz : (size_t)len;
1123 size_t n = fread(in_buf, 1, cnt, stdin);
1124 if (!n && feof(stdin))
1125 die("EOF in data (%" PRIuMAX " bytes remaining)", len);
1127 the_hash_algo->update_fn(&c, in_buf, n);
1128 s.next_in = in_buf;
1129 s.avail_in = n;
1130 len -= n;
1133 status = git_deflate(&s, len ? 0 : Z_FINISH);
1135 if (!s.avail_out || status == Z_STREAM_END) {
1136 size_t n = s.next_out - out_buf;
1137 hashwrite(pack_file, out_buf, n);
1138 pack_size += n;
1139 s.next_out = out_buf;
1140 s.avail_out = out_sz;
1143 switch (status) {
1144 case Z_OK:
1145 case Z_BUF_ERROR:
1146 case Z_STREAM_END:
1147 continue;
1148 default:
1149 die("unexpected deflate failure: %d", status);
1152 git_deflate_end(&s);
1153 the_hash_algo->final_oid_fn(&oid, &c);
1155 if (oidout)
1156 oidcpy(oidout, &oid);
1158 e = insert_object(&oid);
1160 if (mark)
1161 insert_mark(&marks, mark, e);
1163 if (e->idx.offset) {
1164 duplicate_count_by_type[OBJ_BLOB]++;
1165 truncate_pack(&checkpoint);
1167 } else if (find_sha1_pack(oid.hash,
1168 get_all_packs(the_repository))) {
1169 e->type = OBJ_BLOB;
1170 e->pack_id = MAX_PACK_ID;
1171 e->idx.offset = 1; /* just not zero! */
1172 duplicate_count_by_type[OBJ_BLOB]++;
1173 truncate_pack(&checkpoint);
1175 } else {
1176 e->depth = 0;
1177 e->type = OBJ_BLOB;
1178 e->pack_id = pack_id;
1179 e->idx.offset = offset;
1180 e->idx.crc32 = crc32_end(pack_file);
1181 object_count++;
1182 object_count_by_type[OBJ_BLOB]++;
1185 free(in_buf);
1186 free(out_buf);
1189 /* All calls must be guarded by find_object() or find_mark() to
1190 * ensure the 'struct object_entry' passed was written by this
1191 * process instance. We unpack the entry by the offset, avoiding
1192 * the need for the corresponding .idx file. This unpacking rule
1193 * works because we only use OBJ_REF_DELTA within the packfiles
1194 * created by fast-import.
1196 * oe must not be NULL. Such an oe usually comes from giving
1197 * an unknown SHA-1 to find_object() or an undefined mark to
1198 * find_mark(). Callers must test for this condition and use
1199 * the standard read_sha1_file() when it happens.
1201 * oe->pack_id must not be MAX_PACK_ID. Such an oe is usually from
1202 * find_mark(), where the mark was reloaded from an existing marks
1203 * file and is referencing an object that this fast-import process
1204 * instance did not write out to a packfile. Callers must test for
1205 * this condition and use read_sha1_file() instead.
1207 static void *gfi_unpack_entry(
1208 struct object_entry *oe,
1209 unsigned long *sizep)
1211 enum object_type type;
1212 struct packed_git *p = all_packs[oe->pack_id];
1213 if (p == pack_data && p->pack_size < (pack_size + the_hash_algo->rawsz)) {
1214 /* The object is stored in the packfile we are writing to
1215 * and we have modified it since the last time we scanned
1216 * back to read a previously written object. If an old
1217 * window covered [p->pack_size, p->pack_size + rawsz) its
1218 * data is stale and is not valid. Closing all windows
1219 * and updating the packfile length ensures we can read
1220 * the newly written data.
1222 close_pack_windows(p);
1223 hashflush(pack_file);
1225 /* We have to offer rawsz bytes additional on the end of
1226 * the packfile as the core unpacker code assumes the
1227 * footer is present at the file end and must promise
1228 * at least rawsz bytes within any window it maps. But
1229 * we don't actually create the footer here.
1231 p->pack_size = pack_size + the_hash_algo->rawsz;
1233 return unpack_entry(the_repository, p, oe->idx.offset, &type, sizep);
1236 static const char *get_mode(const char *str, uint16_t *modep)
1238 unsigned char c;
1239 uint16_t mode = 0;
1241 while ((c = *str++) != ' ') {
1242 if (c < '0' || c > '7')
1243 return NULL;
1244 mode = (mode << 3) + (c - '0');
1246 *modep = mode;
1247 return str;
1250 static void load_tree(struct tree_entry *root)
1252 struct object_id *oid = &root->versions[1].oid;
1253 struct object_entry *myoe;
1254 struct tree_content *t;
1255 unsigned long size;
1256 char *buf;
1257 const char *c;
1259 root->tree = t = new_tree_content(8);
1260 if (is_null_oid(oid))
1261 return;
1263 myoe = find_object(oid);
1264 if (myoe && myoe->pack_id != MAX_PACK_ID) {
1265 if (myoe->type != OBJ_TREE)
1266 die("Not a tree: %s", oid_to_hex(oid));
1267 t->delta_depth = myoe->depth;
1268 buf = gfi_unpack_entry(myoe, &size);
1269 if (!buf)
1270 die("Can't load tree %s", oid_to_hex(oid));
1271 } else {
1272 enum object_type type;
1273 buf = repo_read_object_file(the_repository, oid, &type, &size);
1274 if (!buf || type != OBJ_TREE)
1275 die("Can't load tree %s", oid_to_hex(oid));
1278 c = buf;
1279 while (c != (buf + size)) {
1280 struct tree_entry *e = new_tree_entry();
1282 if (t->entry_count == t->entry_capacity)
1283 root->tree = t = grow_tree_content(t, t->entry_count);
1284 t->entries[t->entry_count++] = e;
1286 e->tree = NULL;
1287 c = get_mode(c, &e->versions[1].mode);
1288 if (!c)
1289 die("Corrupt mode in %s", oid_to_hex(oid));
1290 e->versions[0].mode = e->versions[1].mode;
1291 e->name = to_atom(c, strlen(c));
1292 c += e->name->str_len + 1;
1293 oidread(&e->versions[0].oid, (unsigned char *)c);
1294 oidread(&e->versions[1].oid, (unsigned char *)c);
1295 c += the_hash_algo->rawsz;
1297 free(buf);
1300 static int tecmp0 (const void *_a, const void *_b)
1302 struct tree_entry *a = *((struct tree_entry**)_a);
1303 struct tree_entry *b = *((struct tree_entry**)_b);
1304 return base_name_compare(
1305 a->name->str_dat, a->name->str_len, a->versions[0].mode,
1306 b->name->str_dat, b->name->str_len, b->versions[0].mode);
1309 static int tecmp1 (const void *_a, const void *_b)
1311 struct tree_entry *a = *((struct tree_entry**)_a);
1312 struct tree_entry *b = *((struct tree_entry**)_b);
1313 return base_name_compare(
1314 a->name->str_dat, a->name->str_len, a->versions[1].mode,
1315 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1318 static void mktree(struct tree_content *t, int v, struct strbuf *b)
1320 size_t maxlen = 0;
1321 unsigned int i;
1323 if (!v)
1324 QSORT(t->entries, t->entry_count, tecmp0);
1325 else
1326 QSORT(t->entries, t->entry_count, tecmp1);
1328 for (i = 0; i < t->entry_count; i++) {
1329 if (t->entries[i]->versions[v].mode)
1330 maxlen += t->entries[i]->name->str_len + 34;
1333 strbuf_reset(b);
1334 strbuf_grow(b, maxlen);
1335 for (i = 0; i < t->entry_count; i++) {
1336 struct tree_entry *e = t->entries[i];
1337 if (!e->versions[v].mode)
1338 continue;
1339 strbuf_addf(b, "%o %s%c",
1340 (unsigned int)(e->versions[v].mode & ~NO_DELTA),
1341 e->name->str_dat, '\0');
1342 strbuf_add(b, e->versions[v].oid.hash, the_hash_algo->rawsz);
1346 static void store_tree(struct tree_entry *root)
1348 struct tree_content *t;
1349 unsigned int i, j, del;
1350 struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1351 struct object_entry *le = NULL;
1353 if (!is_null_oid(&root->versions[1].oid))
1354 return;
1356 if (!root->tree)
1357 load_tree(root);
1358 t = root->tree;
1360 for (i = 0; i < t->entry_count; i++) {
1361 if (t->entries[i]->tree)
1362 store_tree(t->entries[i]);
1365 if (!(root->versions[0].mode & NO_DELTA))
1366 le = find_object(&root->versions[0].oid);
1367 if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1368 mktree(t, 0, &old_tree);
1369 lo.data = old_tree;
1370 lo.offset = le->idx.offset;
1371 lo.depth = t->delta_depth;
1374 mktree(t, 1, &new_tree);
1375 store_object(OBJ_TREE, &new_tree, &lo, &root->versions[1].oid, 0);
1377 t->delta_depth = lo.depth;
1378 for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1379 struct tree_entry *e = t->entries[i];
1380 if (e->versions[1].mode) {
1381 e->versions[0].mode = e->versions[1].mode;
1382 oidcpy(&e->versions[0].oid, &e->versions[1].oid);
1383 t->entries[j++] = e;
1384 } else {
1385 release_tree_entry(e);
1386 del++;
1389 t->entry_count -= del;
1392 static void tree_content_replace(
1393 struct tree_entry *root,
1394 const struct object_id *oid,
1395 const uint16_t mode,
1396 struct tree_content *newtree)
1398 if (!S_ISDIR(mode))
1399 die("Root cannot be a non-directory");
1400 oidclr(&root->versions[0].oid);
1401 oidcpy(&root->versions[1].oid, oid);
1402 if (root->tree)
1403 release_tree_content_recursive(root->tree);
1404 root->tree = newtree;
1407 static int tree_content_set(
1408 struct tree_entry *root,
1409 const char *p,
1410 const struct object_id *oid,
1411 const uint16_t mode,
1412 struct tree_content *subtree)
1414 struct tree_content *t;
1415 const char *slash1;
1416 unsigned int i, n;
1417 struct tree_entry *e;
1419 slash1 = strchrnul(p, '/');
1420 n = slash1 - p;
1421 if (!n)
1422 die("Empty path component found in input");
1423 if (!*slash1 && !S_ISDIR(mode) && subtree)
1424 die("Non-directories cannot have subtrees");
1426 if (!root->tree)
1427 load_tree(root);
1428 t = root->tree;
1429 for (i = 0; i < t->entry_count; i++) {
1430 e = t->entries[i];
1431 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1432 if (!*slash1) {
1433 if (!S_ISDIR(mode)
1434 && e->versions[1].mode == mode
1435 && oideq(&e->versions[1].oid, oid))
1436 return 0;
1437 e->versions[1].mode = mode;
1438 oidcpy(&e->versions[1].oid, oid);
1439 if (e->tree)
1440 release_tree_content_recursive(e->tree);
1441 e->tree = subtree;
1444 * We need to leave e->versions[0].sha1 alone
1445 * to avoid modifying the preimage tree used
1446 * when writing out the parent directory.
1447 * But after replacing the subdir with a
1448 * completely different one, it's not a good
1449 * delta base any more, and besides, we've
1450 * thrown away the tree entries needed to
1451 * make a delta against it.
1453 * So let's just explicitly disable deltas
1454 * for the subtree.
1456 if (S_ISDIR(e->versions[0].mode))
1457 e->versions[0].mode |= NO_DELTA;
1459 oidclr(&root->versions[1].oid);
1460 return 1;
1462 if (!S_ISDIR(e->versions[1].mode)) {
1463 e->tree = new_tree_content(8);
1464 e->versions[1].mode = S_IFDIR;
1466 if (!e->tree)
1467 load_tree(e);
1468 if (tree_content_set(e, slash1 + 1, oid, mode, subtree)) {
1469 oidclr(&root->versions[1].oid);
1470 return 1;
1472 return 0;
1476 if (t->entry_count == t->entry_capacity)
1477 root->tree = t = grow_tree_content(t, t->entry_count);
1478 e = new_tree_entry();
1479 e->name = to_atom(p, n);
1480 e->versions[0].mode = 0;
1481 oidclr(&e->versions[0].oid);
1482 t->entries[t->entry_count++] = e;
1483 if (*slash1) {
1484 e->tree = new_tree_content(8);
1485 e->versions[1].mode = S_IFDIR;
1486 tree_content_set(e, slash1 + 1, oid, mode, subtree);
1487 } else {
1488 e->tree = subtree;
1489 e->versions[1].mode = mode;
1490 oidcpy(&e->versions[1].oid, oid);
1492 oidclr(&root->versions[1].oid);
1493 return 1;
1496 static int tree_content_remove(
1497 struct tree_entry *root,
1498 const char *p,
1499 struct tree_entry *backup_leaf,
1500 int allow_root)
1502 struct tree_content *t;
1503 const char *slash1;
1504 unsigned int i, n;
1505 struct tree_entry *e;
1507 slash1 = strchrnul(p, '/');
1508 n = slash1 - p;
1510 if (!root->tree)
1511 load_tree(root);
1513 if (!*p && allow_root) {
1514 e = root;
1515 goto del_entry;
1518 t = root->tree;
1519 for (i = 0; i < t->entry_count; i++) {
1520 e = t->entries[i];
1521 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1522 if (*slash1 && !S_ISDIR(e->versions[1].mode))
1524 * If p names a file in some subdirectory, and a
1525 * file or symlink matching the name of the
1526 * parent directory of p exists, then p cannot
1527 * exist and need not be deleted.
1529 return 1;
1530 if (!*slash1 || !S_ISDIR(e->versions[1].mode))
1531 goto del_entry;
1532 if (!e->tree)
1533 load_tree(e);
1534 if (tree_content_remove(e, slash1 + 1, backup_leaf, 0)) {
1535 for (n = 0; n < e->tree->entry_count; n++) {
1536 if (e->tree->entries[n]->versions[1].mode) {
1537 oidclr(&root->versions[1].oid);
1538 return 1;
1541 backup_leaf = NULL;
1542 goto del_entry;
1544 return 0;
1547 return 0;
1549 del_entry:
1550 if (backup_leaf)
1551 memcpy(backup_leaf, e, sizeof(*backup_leaf));
1552 else if (e->tree)
1553 release_tree_content_recursive(e->tree);
1554 e->tree = NULL;
1555 e->versions[1].mode = 0;
1556 oidclr(&e->versions[1].oid);
1557 oidclr(&root->versions[1].oid);
1558 return 1;
1561 static int tree_content_get(
1562 struct tree_entry *root,
1563 const char *p,
1564 struct tree_entry *leaf,
1565 int allow_root)
1567 struct tree_content *t;
1568 const char *slash1;
1569 unsigned int i, n;
1570 struct tree_entry *e;
1572 slash1 = strchrnul(p, '/');
1573 n = slash1 - p;
1574 if (!n && !allow_root)
1575 die("Empty path component found in input");
1577 if (!root->tree)
1578 load_tree(root);
1580 if (!n) {
1581 e = root;
1582 goto found_entry;
1585 t = root->tree;
1586 for (i = 0; i < t->entry_count; i++) {
1587 e = t->entries[i];
1588 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1589 if (!*slash1)
1590 goto found_entry;
1591 if (!S_ISDIR(e->versions[1].mode))
1592 return 0;
1593 if (!e->tree)
1594 load_tree(e);
1595 return tree_content_get(e, slash1 + 1, leaf, 0);
1598 return 0;
1600 found_entry:
1601 memcpy(leaf, e, sizeof(*leaf));
1602 if (e->tree && is_null_oid(&e->versions[1].oid))
1603 leaf->tree = dup_tree_content(e->tree);
1604 else
1605 leaf->tree = NULL;
1606 return 1;
1609 static int update_branch(struct branch *b)
1611 static const char *msg = "fast-import";
1612 struct ref_transaction *transaction;
1613 struct object_id old_oid;
1614 struct strbuf err = STRBUF_INIT;
1616 if (is_null_oid(&b->oid)) {
1617 if (b->delete)
1618 delete_ref(NULL, b->name, NULL, 0);
1619 return 0;
1621 if (read_ref(b->name, &old_oid))
1622 oidclr(&old_oid);
1623 if (!force_update && !is_null_oid(&old_oid)) {
1624 struct commit *old_cmit, *new_cmit;
1626 old_cmit = lookup_commit_reference_gently(the_repository,
1627 &old_oid, 0);
1628 new_cmit = lookup_commit_reference_gently(the_repository,
1629 &b->oid, 0);
1630 if (!old_cmit || !new_cmit)
1631 return error("Branch %s is missing commits.", b->name);
1633 if (!repo_in_merge_bases(the_repository, old_cmit, new_cmit)) {
1634 warning("Not updating %s"
1635 " (new tip %s does not contain %s)",
1636 b->name, oid_to_hex(&b->oid),
1637 oid_to_hex(&old_oid));
1638 return -1;
1641 transaction = ref_transaction_begin(&err);
1642 if (!transaction ||
1643 ref_transaction_update(transaction, b->name, &b->oid, &old_oid,
1644 0, msg, &err) ||
1645 ref_transaction_commit(transaction, &err)) {
1646 ref_transaction_free(transaction);
1647 error("%s", err.buf);
1648 strbuf_release(&err);
1649 return -1;
1651 ref_transaction_free(transaction);
1652 strbuf_release(&err);
1653 return 0;
1656 static void dump_branches(void)
1658 unsigned int i;
1659 struct branch *b;
1661 for (i = 0; i < branch_table_sz; i++) {
1662 for (b = branch_table[i]; b; b = b->table_next_branch)
1663 failure |= update_branch(b);
1667 static void dump_tags(void)
1669 static const char *msg = "fast-import";
1670 struct tag *t;
1671 struct strbuf ref_name = STRBUF_INIT;
1672 struct strbuf err = STRBUF_INIT;
1673 struct ref_transaction *transaction;
1675 transaction = ref_transaction_begin(&err);
1676 if (!transaction) {
1677 failure |= error("%s", err.buf);
1678 goto cleanup;
1680 for (t = first_tag; t; t = t->next_tag) {
1681 strbuf_reset(&ref_name);
1682 strbuf_addf(&ref_name, "refs/tags/%s", t->name);
1684 if (ref_transaction_update(transaction, ref_name.buf,
1685 &t->oid, NULL, 0, msg, &err)) {
1686 failure |= error("%s", err.buf);
1687 goto cleanup;
1690 if (ref_transaction_commit(transaction, &err))
1691 failure |= error("%s", err.buf);
1693 cleanup:
1694 ref_transaction_free(transaction);
1695 strbuf_release(&ref_name);
1696 strbuf_release(&err);
1699 static void dump_marks(void)
1701 struct lock_file mark_lock = LOCK_INIT;
1702 FILE *f;
1704 if (!export_marks_file || (import_marks_file && !import_marks_file_done))
1705 return;
1707 if (safe_create_leading_directories_const(export_marks_file)) {
1708 failure |= error_errno("unable to create leading directories of %s",
1709 export_marks_file);
1710 return;
1713 if (hold_lock_file_for_update(&mark_lock, export_marks_file, 0) < 0) {
1714 failure |= error_errno("Unable to write marks file %s",
1715 export_marks_file);
1716 return;
1719 f = fdopen_lock_file(&mark_lock, "w");
1720 if (!f) {
1721 int saved_errno = errno;
1722 rollback_lock_file(&mark_lock);
1723 failure |= error("Unable to write marks file %s: %s",
1724 export_marks_file, strerror(saved_errno));
1725 return;
1728 for_each_mark(marks, 0, dump_marks_fn, f);
1729 if (commit_lock_file(&mark_lock)) {
1730 failure |= error_errno("Unable to write file %s",
1731 export_marks_file);
1732 return;
1736 static void insert_object_entry(struct mark_set **s, struct object_id *oid, uintmax_t mark)
1738 struct object_entry *e;
1739 e = find_object(oid);
1740 if (!e) {
1741 enum object_type type = oid_object_info(the_repository,
1742 oid, NULL);
1743 if (type < 0)
1744 die("object not found: %s", oid_to_hex(oid));
1745 e = insert_object(oid);
1746 e->type = type;
1747 e->pack_id = MAX_PACK_ID;
1748 e->idx.offset = 1; /* just not zero! */
1750 insert_mark(s, mark, e);
1753 static void insert_oid_entry(struct mark_set **s, struct object_id *oid, uintmax_t mark)
1755 insert_mark(s, mark, xmemdupz(oid, sizeof(*oid)));
1758 static void read_mark_file(struct mark_set **s, FILE *f, mark_set_inserter_t inserter)
1760 char line[512];
1761 while (fgets(line, sizeof(line), f)) {
1762 uintmax_t mark;
1763 char *end;
1764 struct object_id oid;
1766 /* Ensure SHA-1 objects are padded with zeros. */
1767 memset(oid.hash, 0, sizeof(oid.hash));
1769 end = strchr(line, '\n');
1770 if (line[0] != ':' || !end)
1771 die("corrupt mark line: %s", line);
1772 *end = 0;
1773 mark = strtoumax(line + 1, &end, 10);
1774 if (!mark || end == line + 1
1775 || *end != ' '
1776 || get_oid_hex_any(end + 1, &oid) == GIT_HASH_UNKNOWN)
1777 die("corrupt mark line: %s", line);
1778 inserter(s, &oid, mark);
1782 static void read_marks(void)
1784 FILE *f = fopen(import_marks_file, "r");
1785 if (f)
1787 else if (import_marks_file_ignore_missing && errno == ENOENT)
1788 goto done; /* Marks file does not exist */
1789 else
1790 die_errno("cannot read '%s'", import_marks_file);
1791 read_mark_file(&marks, f, insert_object_entry);
1792 fclose(f);
1793 done:
1794 import_marks_file_done = 1;
1798 static int read_next_command(void)
1800 static int stdin_eof = 0;
1802 if (stdin_eof) {
1803 unread_command_buf = 0;
1804 return EOF;
1807 for (;;) {
1808 if (unread_command_buf) {
1809 unread_command_buf = 0;
1810 } else {
1811 struct recent_command *rc;
1813 stdin_eof = strbuf_getline_lf(&command_buf, stdin);
1814 if (stdin_eof)
1815 return EOF;
1817 if (!seen_data_command
1818 && !starts_with(command_buf.buf, "feature ")
1819 && !starts_with(command_buf.buf, "option ")) {
1820 parse_argv();
1823 rc = rc_free;
1824 if (rc)
1825 rc_free = rc->next;
1826 else {
1827 rc = cmd_hist.next;
1828 cmd_hist.next = rc->next;
1829 cmd_hist.next->prev = &cmd_hist;
1830 free(rc->buf);
1833 rc->buf = xstrdup(command_buf.buf);
1834 rc->prev = cmd_tail;
1835 rc->next = cmd_hist.prev;
1836 rc->prev->next = rc;
1837 cmd_tail = rc;
1839 if (command_buf.buf[0] == '#')
1840 continue;
1841 return 0;
1845 static void skip_optional_lf(void)
1847 int term_char = fgetc(stdin);
1848 if (term_char != '\n' && term_char != EOF)
1849 ungetc(term_char, stdin);
1852 static void parse_mark(void)
1854 const char *v;
1855 if (skip_prefix(command_buf.buf, "mark :", &v)) {
1856 next_mark = strtoumax(v, NULL, 10);
1857 read_next_command();
1859 else
1860 next_mark = 0;
1863 static void parse_original_identifier(void)
1865 const char *v;
1866 if (skip_prefix(command_buf.buf, "original-oid ", &v))
1867 read_next_command();
1870 static int parse_data(struct strbuf *sb, uintmax_t limit, uintmax_t *len_res)
1872 const char *data;
1873 strbuf_reset(sb);
1875 if (!skip_prefix(command_buf.buf, "data ", &data))
1876 die("Expected 'data n' command, found: %s", command_buf.buf);
1878 if (skip_prefix(data, "<<", &data)) {
1879 char *term = xstrdup(data);
1880 size_t term_len = command_buf.len - (data - command_buf.buf);
1882 for (;;) {
1883 if (strbuf_getline_lf(&command_buf, stdin) == EOF)
1884 die("EOF in data (terminator '%s' not found)", term);
1885 if (term_len == command_buf.len
1886 && !strcmp(term, command_buf.buf))
1887 break;
1888 strbuf_addbuf(sb, &command_buf);
1889 strbuf_addch(sb, '\n');
1891 free(term);
1893 else {
1894 uintmax_t len = strtoumax(data, NULL, 10);
1895 size_t n = 0, length = (size_t)len;
1897 if (limit && limit < len) {
1898 *len_res = len;
1899 return 0;
1901 if (length < len)
1902 die("data is too large to use in this context");
1904 while (n < length) {
1905 size_t s = strbuf_fread(sb, length - n, stdin);
1906 if (!s && feof(stdin))
1907 die("EOF in data (%lu bytes remaining)",
1908 (unsigned long)(length - n));
1909 n += s;
1913 skip_optional_lf();
1914 return 1;
1917 static int validate_raw_date(const char *src, struct strbuf *result, int strict)
1919 const char *orig_src = src;
1920 char *endp;
1921 unsigned long num;
1923 errno = 0;
1925 num = strtoul(src, &endp, 10);
1927 * NEEDSWORK: perhaps check for reasonable values? For example, we
1928 * could error on values representing times more than a
1929 * day in the future.
1931 if (errno || endp == src || *endp != ' ')
1932 return -1;
1934 src = endp + 1;
1935 if (*src != '-' && *src != '+')
1936 return -1;
1938 num = strtoul(src + 1, &endp, 10);
1940 * NEEDSWORK: check for brokenness other than num > 1400, such as
1941 * (num % 100) >= 60, or ((num % 100) % 15) != 0 ?
1943 if (errno || endp == src + 1 || *endp || /* did not parse */
1944 (strict && (1400 < num)) /* parsed a broken timezone */
1946 return -1;
1948 strbuf_addstr(result, orig_src);
1949 return 0;
1952 static char *parse_ident(const char *buf)
1954 const char *ltgt;
1955 size_t name_len;
1956 struct strbuf ident = STRBUF_INIT;
1958 /* ensure there is a space delimiter even if there is no name */
1959 if (*buf == '<')
1960 --buf;
1962 ltgt = buf + strcspn(buf, "<>");
1963 if (*ltgt != '<')
1964 die("Missing < in ident string: %s", buf);
1965 if (ltgt != buf && ltgt[-1] != ' ')
1966 die("Missing space before < in ident string: %s", buf);
1967 ltgt = ltgt + 1 + strcspn(ltgt + 1, "<>");
1968 if (*ltgt != '>')
1969 die("Missing > in ident string: %s", buf);
1970 ltgt++;
1971 if (*ltgt != ' ')
1972 die("Missing space after > in ident string: %s", buf);
1973 ltgt++;
1974 name_len = ltgt - buf;
1975 strbuf_add(&ident, buf, name_len);
1977 switch (whenspec) {
1978 case WHENSPEC_RAW:
1979 if (validate_raw_date(ltgt, &ident, 1) < 0)
1980 die("Invalid raw date \"%s\" in ident: %s", ltgt, buf);
1981 break;
1982 case WHENSPEC_RAW_PERMISSIVE:
1983 if (validate_raw_date(ltgt, &ident, 0) < 0)
1984 die("Invalid raw date \"%s\" in ident: %s", ltgt, buf);
1985 break;
1986 case WHENSPEC_RFC2822:
1987 if (parse_date(ltgt, &ident) < 0)
1988 die("Invalid rfc2822 date \"%s\" in ident: %s", ltgt, buf);
1989 break;
1990 case WHENSPEC_NOW:
1991 if (strcmp("now", ltgt))
1992 die("Date in ident must be 'now': %s", buf);
1993 datestamp(&ident);
1994 break;
1997 return strbuf_detach(&ident, NULL);
2000 static void parse_and_store_blob(
2001 struct last_object *last,
2002 struct object_id *oidout,
2003 uintmax_t mark)
2005 static struct strbuf buf = STRBUF_INIT;
2006 uintmax_t len;
2008 if (parse_data(&buf, big_file_threshold, &len))
2009 store_object(OBJ_BLOB, &buf, last, oidout, mark);
2010 else {
2011 if (last) {
2012 strbuf_release(&last->data);
2013 last->offset = 0;
2014 last->depth = 0;
2016 stream_blob(len, oidout, mark);
2017 skip_optional_lf();
2021 static void parse_new_blob(void)
2023 read_next_command();
2024 parse_mark();
2025 parse_original_identifier();
2026 parse_and_store_blob(&last_blob, NULL, next_mark);
2029 static void unload_one_branch(void)
2031 while (cur_active_branches
2032 && cur_active_branches >= max_active_branches) {
2033 uintmax_t min_commit = ULONG_MAX;
2034 struct branch *e, *l = NULL, *p = NULL;
2036 for (e = active_branches; e; e = e->active_next_branch) {
2037 if (e->last_commit < min_commit) {
2038 p = l;
2039 min_commit = e->last_commit;
2041 l = e;
2044 if (p) {
2045 e = p->active_next_branch;
2046 p->active_next_branch = e->active_next_branch;
2047 } else {
2048 e = active_branches;
2049 active_branches = e->active_next_branch;
2051 e->active = 0;
2052 e->active_next_branch = NULL;
2053 if (e->branch_tree.tree) {
2054 release_tree_content_recursive(e->branch_tree.tree);
2055 e->branch_tree.tree = NULL;
2057 cur_active_branches--;
2061 static void load_branch(struct branch *b)
2063 load_tree(&b->branch_tree);
2064 if (!b->active) {
2065 b->active = 1;
2066 b->active_next_branch = active_branches;
2067 active_branches = b;
2068 cur_active_branches++;
2069 branch_load_count++;
2073 static unsigned char convert_num_notes_to_fanout(uintmax_t num_notes)
2075 unsigned char fanout = 0;
2076 while ((num_notes >>= 8))
2077 fanout++;
2078 return fanout;
2081 static void construct_path_with_fanout(const char *hex_sha1,
2082 unsigned char fanout, char *path)
2084 unsigned int i = 0, j = 0;
2085 if (fanout >= the_hash_algo->rawsz)
2086 die("Too large fanout (%u)", fanout);
2087 while (fanout) {
2088 path[i++] = hex_sha1[j++];
2089 path[i++] = hex_sha1[j++];
2090 path[i++] = '/';
2091 fanout--;
2093 memcpy(path + i, hex_sha1 + j, the_hash_algo->hexsz - j);
2094 path[i + the_hash_algo->hexsz - j] = '\0';
2097 static uintmax_t do_change_note_fanout(
2098 struct tree_entry *orig_root, struct tree_entry *root,
2099 char *hex_oid, unsigned int hex_oid_len,
2100 char *fullpath, unsigned int fullpath_len,
2101 unsigned char fanout)
2103 struct tree_content *t;
2104 struct tree_entry *e, leaf;
2105 unsigned int i, tmp_hex_oid_len, tmp_fullpath_len;
2106 uintmax_t num_notes = 0;
2107 struct object_id oid;
2108 /* hex oid + '/' between each pair of hex digits + NUL */
2109 char realpath[GIT_MAX_HEXSZ + ((GIT_MAX_HEXSZ / 2) - 1) + 1];
2110 const unsigned hexsz = the_hash_algo->hexsz;
2112 if (!root->tree)
2113 load_tree(root);
2114 t = root->tree;
2116 for (i = 0; t && i < t->entry_count; i++) {
2117 e = t->entries[i];
2118 tmp_hex_oid_len = hex_oid_len + e->name->str_len;
2119 tmp_fullpath_len = fullpath_len;
2122 * We're interested in EITHER existing note entries (entries
2123 * with exactly 40 hex chars in path, not including directory
2124 * separators), OR directory entries that may contain note
2125 * entries (with < 40 hex chars in path).
2126 * Also, each path component in a note entry must be a multiple
2127 * of 2 chars.
2129 if (!e->versions[1].mode ||
2130 tmp_hex_oid_len > hexsz ||
2131 e->name->str_len % 2)
2132 continue;
2134 /* This _may_ be a note entry, or a subdir containing notes */
2135 memcpy(hex_oid + hex_oid_len, e->name->str_dat,
2136 e->name->str_len);
2137 if (tmp_fullpath_len)
2138 fullpath[tmp_fullpath_len++] = '/';
2139 memcpy(fullpath + tmp_fullpath_len, e->name->str_dat,
2140 e->name->str_len);
2141 tmp_fullpath_len += e->name->str_len;
2142 fullpath[tmp_fullpath_len] = '\0';
2144 if (tmp_hex_oid_len == hexsz && !get_oid_hex(hex_oid, &oid)) {
2145 /* This is a note entry */
2146 if (fanout == 0xff) {
2147 /* Counting mode, no rename */
2148 num_notes++;
2149 continue;
2151 construct_path_with_fanout(hex_oid, fanout, realpath);
2152 if (!strcmp(fullpath, realpath)) {
2153 /* Note entry is in correct location */
2154 num_notes++;
2155 continue;
2158 /* Rename fullpath to realpath */
2159 if (!tree_content_remove(orig_root, fullpath, &leaf, 0))
2160 die("Failed to remove path %s", fullpath);
2161 tree_content_set(orig_root, realpath,
2162 &leaf.versions[1].oid,
2163 leaf.versions[1].mode,
2164 leaf.tree);
2165 } else if (S_ISDIR(e->versions[1].mode)) {
2166 /* This is a subdir that may contain note entries */
2167 num_notes += do_change_note_fanout(orig_root, e,
2168 hex_oid, tmp_hex_oid_len,
2169 fullpath, tmp_fullpath_len, fanout);
2172 /* The above may have reallocated the current tree_content */
2173 t = root->tree;
2175 return num_notes;
2178 static uintmax_t change_note_fanout(struct tree_entry *root,
2179 unsigned char fanout)
2182 * The size of path is due to one slash between every two hex digits,
2183 * plus the terminating NUL. Note that there is no slash at the end, so
2184 * the number of slashes is one less than half the number of hex
2185 * characters.
2187 char hex_oid[GIT_MAX_HEXSZ], path[GIT_MAX_HEXSZ + (GIT_MAX_HEXSZ / 2) - 1 + 1];
2188 return do_change_note_fanout(root, root, hex_oid, 0, path, 0, fanout);
2191 static int parse_mapped_oid_hex(const char *hex, struct object_id *oid, const char **end)
2193 int algo;
2194 khiter_t it;
2196 /* Make SHA-1 object IDs have all-zero padding. */
2197 memset(oid->hash, 0, sizeof(oid->hash));
2199 algo = parse_oid_hex_any(hex, oid, end);
2200 if (algo == GIT_HASH_UNKNOWN)
2201 return -1;
2203 it = kh_get_oid_map(sub_oid_map, *oid);
2204 /* No such object? */
2205 if (it == kh_end(sub_oid_map)) {
2206 /* If we're using the same algorithm, pass it through. */
2207 if (hash_algos[algo].format_id == the_hash_algo->format_id)
2208 return 0;
2209 return -1;
2211 oidcpy(oid, kh_value(sub_oid_map, it));
2212 return 0;
2216 * Given a pointer into a string, parse a mark reference:
2218 * idnum ::= ':' bigint;
2220 * Return the first character after the value in *endptr.
2222 * Complain if the following character is not what is expected,
2223 * either a space or end of the string.
2225 static uintmax_t parse_mark_ref(const char *p, char **endptr)
2227 uintmax_t mark;
2229 assert(*p == ':');
2230 p++;
2231 mark = strtoumax(p, endptr, 10);
2232 if (*endptr == p)
2233 die("No value after ':' in mark: %s", command_buf.buf);
2234 return mark;
2238 * Parse the mark reference, and complain if this is not the end of
2239 * the string.
2241 static uintmax_t parse_mark_ref_eol(const char *p)
2243 char *end;
2244 uintmax_t mark;
2246 mark = parse_mark_ref(p, &end);
2247 if (*end != '\0')
2248 die("Garbage after mark: %s", command_buf.buf);
2249 return mark;
2253 * Parse the mark reference, demanding a trailing space. Return a
2254 * pointer to the space.
2256 static uintmax_t parse_mark_ref_space(const char **p)
2258 uintmax_t mark;
2259 char *end;
2261 mark = parse_mark_ref(*p, &end);
2262 if (*end++ != ' ')
2263 die("Missing space after mark: %s", command_buf.buf);
2264 *p = end;
2265 return mark;
2268 static void file_change_m(const char *p, struct branch *b)
2270 static struct strbuf uq = STRBUF_INIT;
2271 const char *endp;
2272 struct object_entry *oe;
2273 struct object_id oid;
2274 uint16_t mode, inline_data = 0;
2276 p = get_mode(p, &mode);
2277 if (!p)
2278 die("Corrupt mode: %s", command_buf.buf);
2279 switch (mode) {
2280 case 0644:
2281 case 0755:
2282 mode |= S_IFREG;
2283 case S_IFREG | 0644:
2284 case S_IFREG | 0755:
2285 case S_IFLNK:
2286 case S_IFDIR:
2287 case S_IFGITLINK:
2288 /* ok */
2289 break;
2290 default:
2291 die("Corrupt mode: %s", command_buf.buf);
2294 if (*p == ':') {
2295 oe = find_mark(marks, parse_mark_ref_space(&p));
2296 oidcpy(&oid, &oe->idx.oid);
2297 } else if (skip_prefix(p, "inline ", &p)) {
2298 inline_data = 1;
2299 oe = NULL; /* not used with inline_data, but makes gcc happy */
2300 } else {
2301 if (parse_mapped_oid_hex(p, &oid, &p))
2302 die("Invalid dataref: %s", command_buf.buf);
2303 oe = find_object(&oid);
2304 if (*p++ != ' ')
2305 die("Missing space after SHA1: %s", command_buf.buf);
2308 strbuf_reset(&uq);
2309 if (!unquote_c_style(&uq, p, &endp)) {
2310 if (*endp)
2311 die("Garbage after path in: %s", command_buf.buf);
2312 p = uq.buf;
2315 /* Git does not track empty, non-toplevel directories. */
2316 if (S_ISDIR(mode) && is_empty_tree_oid(&oid) && *p) {
2317 tree_content_remove(&b->branch_tree, p, NULL, 0);
2318 return;
2321 if (S_ISGITLINK(mode)) {
2322 if (inline_data)
2323 die("Git links cannot be specified 'inline': %s",
2324 command_buf.buf);
2325 else if (oe) {
2326 if (oe->type != OBJ_COMMIT)
2327 die("Not a commit (actually a %s): %s",
2328 type_name(oe->type), command_buf.buf);
2331 * Accept the sha1 without checking; it expected to be in
2332 * another repository.
2334 } else if (inline_data) {
2335 if (S_ISDIR(mode))
2336 die("Directories cannot be specified 'inline': %s",
2337 command_buf.buf);
2338 if (p != uq.buf) {
2339 strbuf_addstr(&uq, p);
2340 p = uq.buf;
2342 while (read_next_command() != EOF) {
2343 const char *v;
2344 if (skip_prefix(command_buf.buf, "cat-blob ", &v))
2345 parse_cat_blob(v);
2346 else {
2347 parse_and_store_blob(&last_blob, &oid, 0);
2348 break;
2351 } else {
2352 enum object_type expected = S_ISDIR(mode) ?
2353 OBJ_TREE: OBJ_BLOB;
2354 enum object_type type = oe ? oe->type :
2355 oid_object_info(the_repository, &oid,
2356 NULL);
2357 if (type < 0)
2358 die("%s not found: %s",
2359 S_ISDIR(mode) ? "Tree" : "Blob",
2360 command_buf.buf);
2361 if (type != expected)
2362 die("Not a %s (actually a %s): %s",
2363 type_name(expected), type_name(type),
2364 command_buf.buf);
2367 if (!*p) {
2368 tree_content_replace(&b->branch_tree, &oid, mode, NULL);
2369 return;
2371 tree_content_set(&b->branch_tree, p, &oid, mode, NULL);
2374 static void file_change_d(const char *p, struct branch *b)
2376 static struct strbuf uq = STRBUF_INIT;
2377 const char *endp;
2379 strbuf_reset(&uq);
2380 if (!unquote_c_style(&uq, p, &endp)) {
2381 if (*endp)
2382 die("Garbage after path in: %s", command_buf.buf);
2383 p = uq.buf;
2385 tree_content_remove(&b->branch_tree, p, NULL, 1);
2388 static void file_change_cr(const char *s, struct branch *b, int rename)
2390 const char *d;
2391 static struct strbuf s_uq = STRBUF_INIT;
2392 static struct strbuf d_uq = STRBUF_INIT;
2393 const char *endp;
2394 struct tree_entry leaf;
2396 strbuf_reset(&s_uq);
2397 if (!unquote_c_style(&s_uq, s, &endp)) {
2398 if (*endp != ' ')
2399 die("Missing space after source: %s", command_buf.buf);
2400 } else {
2401 endp = strchr(s, ' ');
2402 if (!endp)
2403 die("Missing space after source: %s", command_buf.buf);
2404 strbuf_add(&s_uq, s, endp - s);
2406 s = s_uq.buf;
2408 endp++;
2409 if (!*endp)
2410 die("Missing dest: %s", command_buf.buf);
2412 d = endp;
2413 strbuf_reset(&d_uq);
2414 if (!unquote_c_style(&d_uq, d, &endp)) {
2415 if (*endp)
2416 die("Garbage after dest in: %s", command_buf.buf);
2417 d = d_uq.buf;
2420 memset(&leaf, 0, sizeof(leaf));
2421 if (rename)
2422 tree_content_remove(&b->branch_tree, s, &leaf, 1);
2423 else
2424 tree_content_get(&b->branch_tree, s, &leaf, 1);
2425 if (!leaf.versions[1].mode)
2426 die("Path %s not in branch", s);
2427 if (!*d) { /* C "path/to/subdir" "" */
2428 tree_content_replace(&b->branch_tree,
2429 &leaf.versions[1].oid,
2430 leaf.versions[1].mode,
2431 leaf.tree);
2432 return;
2434 tree_content_set(&b->branch_tree, d,
2435 &leaf.versions[1].oid,
2436 leaf.versions[1].mode,
2437 leaf.tree);
2440 static void note_change_n(const char *p, struct branch *b, unsigned char *old_fanout)
2442 static struct strbuf uq = STRBUF_INIT;
2443 struct object_entry *oe;
2444 struct branch *s;
2445 struct object_id oid, commit_oid;
2446 char path[GIT_MAX_RAWSZ * 3];
2447 uint16_t inline_data = 0;
2448 unsigned char new_fanout;
2451 * When loading a branch, we don't traverse its tree to count the real
2452 * number of notes (too expensive to do this for all non-note refs).
2453 * This means that recently loaded notes refs might incorrectly have
2454 * b->num_notes == 0, and consequently, old_fanout might be wrong.
2456 * Fix this by traversing the tree and counting the number of notes
2457 * when b->num_notes == 0. If the notes tree is truly empty, the
2458 * calculation should not take long.
2460 if (b->num_notes == 0 && *old_fanout == 0) {
2461 /* Invoke change_note_fanout() in "counting mode". */
2462 b->num_notes = change_note_fanout(&b->branch_tree, 0xff);
2463 *old_fanout = convert_num_notes_to_fanout(b->num_notes);
2466 /* Now parse the notemodify command. */
2467 /* <dataref> or 'inline' */
2468 if (*p == ':') {
2469 oe = find_mark(marks, parse_mark_ref_space(&p));
2470 oidcpy(&oid, &oe->idx.oid);
2471 } else if (skip_prefix(p, "inline ", &p)) {
2472 inline_data = 1;
2473 oe = NULL; /* not used with inline_data, but makes gcc happy */
2474 } else {
2475 if (parse_mapped_oid_hex(p, &oid, &p))
2476 die("Invalid dataref: %s", command_buf.buf);
2477 oe = find_object(&oid);
2478 if (*p++ != ' ')
2479 die("Missing space after SHA1: %s", command_buf.buf);
2482 /* <commit-ish> */
2483 s = lookup_branch(p);
2484 if (s) {
2485 if (is_null_oid(&s->oid))
2486 die("Can't add a note on empty branch.");
2487 oidcpy(&commit_oid, &s->oid);
2488 } else if (*p == ':') {
2489 uintmax_t commit_mark = parse_mark_ref_eol(p);
2490 struct object_entry *commit_oe = find_mark(marks, commit_mark);
2491 if (commit_oe->type != OBJ_COMMIT)
2492 die("Mark :%" PRIuMAX " not a commit", commit_mark);
2493 oidcpy(&commit_oid, &commit_oe->idx.oid);
2494 } else if (!repo_get_oid(the_repository, p, &commit_oid)) {
2495 unsigned long size;
2496 char *buf = read_object_with_reference(the_repository,
2497 &commit_oid,
2498 OBJ_COMMIT, &size,
2499 &commit_oid);
2500 if (!buf || size < the_hash_algo->hexsz + 6)
2501 die("Not a valid commit: %s", p);
2502 free(buf);
2503 } else
2504 die("Invalid ref name or SHA1 expression: %s", p);
2506 if (inline_data) {
2507 if (p != uq.buf) {
2508 strbuf_addstr(&uq, p);
2509 p = uq.buf;
2511 read_next_command();
2512 parse_and_store_blob(&last_blob, &oid, 0);
2513 } else if (oe) {
2514 if (oe->type != OBJ_BLOB)
2515 die("Not a blob (actually a %s): %s",
2516 type_name(oe->type), command_buf.buf);
2517 } else if (!is_null_oid(&oid)) {
2518 enum object_type type = oid_object_info(the_repository, &oid,
2519 NULL);
2520 if (type < 0)
2521 die("Blob not found: %s", command_buf.buf);
2522 if (type != OBJ_BLOB)
2523 die("Not a blob (actually a %s): %s",
2524 type_name(type), command_buf.buf);
2527 construct_path_with_fanout(oid_to_hex(&commit_oid), *old_fanout, path);
2528 if (tree_content_remove(&b->branch_tree, path, NULL, 0))
2529 b->num_notes--;
2531 if (is_null_oid(&oid))
2532 return; /* nothing to insert */
2534 b->num_notes++;
2535 new_fanout = convert_num_notes_to_fanout(b->num_notes);
2536 construct_path_with_fanout(oid_to_hex(&commit_oid), new_fanout, path);
2537 tree_content_set(&b->branch_tree, path, &oid, S_IFREG | 0644, NULL);
2540 static void file_change_deleteall(struct branch *b)
2542 release_tree_content_recursive(b->branch_tree.tree);
2543 oidclr(&b->branch_tree.versions[0].oid);
2544 oidclr(&b->branch_tree.versions[1].oid);
2545 load_tree(&b->branch_tree);
2546 b->num_notes = 0;
2549 static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2551 if (!buf || size < the_hash_algo->hexsz + 6)
2552 die("Not a valid commit: %s", oid_to_hex(&b->oid));
2553 if (memcmp("tree ", buf, 5)
2554 || get_oid_hex(buf + 5, &b->branch_tree.versions[1].oid))
2555 die("The commit %s is corrupt", oid_to_hex(&b->oid));
2556 oidcpy(&b->branch_tree.versions[0].oid,
2557 &b->branch_tree.versions[1].oid);
2560 static void parse_from_existing(struct branch *b)
2562 if (is_null_oid(&b->oid)) {
2563 oidclr(&b->branch_tree.versions[0].oid);
2564 oidclr(&b->branch_tree.versions[1].oid);
2565 } else {
2566 unsigned long size;
2567 char *buf;
2569 buf = read_object_with_reference(the_repository,
2570 &b->oid, OBJ_COMMIT, &size,
2571 &b->oid);
2572 parse_from_commit(b, buf, size);
2573 free(buf);
2577 static int parse_objectish(struct branch *b, const char *objectish)
2579 struct branch *s;
2580 struct object_id oid;
2582 oidcpy(&oid, &b->branch_tree.versions[1].oid);
2584 s = lookup_branch(objectish);
2585 if (b == s)
2586 die("Can't create a branch from itself: %s", b->name);
2587 else if (s) {
2588 struct object_id *t = &s->branch_tree.versions[1].oid;
2589 oidcpy(&b->oid, &s->oid);
2590 oidcpy(&b->branch_tree.versions[0].oid, t);
2591 oidcpy(&b->branch_tree.versions[1].oid, t);
2592 } else if (*objectish == ':') {
2593 uintmax_t idnum = parse_mark_ref_eol(objectish);
2594 struct object_entry *oe = find_mark(marks, idnum);
2595 if (oe->type != OBJ_COMMIT)
2596 die("Mark :%" PRIuMAX " not a commit", idnum);
2597 if (!oideq(&b->oid, &oe->idx.oid)) {
2598 oidcpy(&b->oid, &oe->idx.oid);
2599 if (oe->pack_id != MAX_PACK_ID) {
2600 unsigned long size;
2601 char *buf = gfi_unpack_entry(oe, &size);
2602 parse_from_commit(b, buf, size);
2603 free(buf);
2604 } else
2605 parse_from_existing(b);
2607 } else if (!repo_get_oid(the_repository, objectish, &b->oid)) {
2608 parse_from_existing(b);
2609 if (is_null_oid(&b->oid))
2610 b->delete = 1;
2612 else
2613 die("Invalid ref name or SHA1 expression: %s", objectish);
2615 if (b->branch_tree.tree && !oideq(&oid, &b->branch_tree.versions[1].oid)) {
2616 release_tree_content_recursive(b->branch_tree.tree);
2617 b->branch_tree.tree = NULL;
2620 read_next_command();
2621 return 1;
2624 static int parse_from(struct branch *b)
2626 const char *from;
2628 if (!skip_prefix(command_buf.buf, "from ", &from))
2629 return 0;
2631 return parse_objectish(b, from);
2634 static int parse_objectish_with_prefix(struct branch *b, const char *prefix)
2636 const char *base;
2638 if (!skip_prefix(command_buf.buf, prefix, &base))
2639 return 0;
2641 return parse_objectish(b, base);
2644 static struct hash_list *parse_merge(unsigned int *count)
2646 struct hash_list *list = NULL, **tail = &list, *n;
2647 const char *from;
2648 struct branch *s;
2650 *count = 0;
2651 while (skip_prefix(command_buf.buf, "merge ", &from)) {
2652 n = xmalloc(sizeof(*n));
2653 s = lookup_branch(from);
2654 if (s)
2655 oidcpy(&n->oid, &s->oid);
2656 else if (*from == ':') {
2657 uintmax_t idnum = parse_mark_ref_eol(from);
2658 struct object_entry *oe = find_mark(marks, idnum);
2659 if (oe->type != OBJ_COMMIT)
2660 die("Mark :%" PRIuMAX " not a commit", idnum);
2661 oidcpy(&n->oid, &oe->idx.oid);
2662 } else if (!repo_get_oid(the_repository, from, &n->oid)) {
2663 unsigned long size;
2664 char *buf = read_object_with_reference(the_repository,
2665 &n->oid,
2666 OBJ_COMMIT,
2667 &size, &n->oid);
2668 if (!buf || size < the_hash_algo->hexsz + 6)
2669 die("Not a valid commit: %s", from);
2670 free(buf);
2671 } else
2672 die("Invalid ref name or SHA1 expression: %s", from);
2674 n->next = NULL;
2675 *tail = n;
2676 tail = &n->next;
2678 (*count)++;
2679 read_next_command();
2681 return list;
2684 static void parse_new_commit(const char *arg)
2686 static struct strbuf msg = STRBUF_INIT;
2687 struct branch *b;
2688 char *author = NULL;
2689 char *committer = NULL;
2690 char *encoding = NULL;
2691 struct hash_list *merge_list = NULL;
2692 unsigned int merge_count;
2693 unsigned char prev_fanout, new_fanout;
2694 const char *v;
2696 b = lookup_branch(arg);
2697 if (!b)
2698 b = new_branch(arg);
2700 read_next_command();
2701 parse_mark();
2702 parse_original_identifier();
2703 if (skip_prefix(command_buf.buf, "author ", &v)) {
2704 author = parse_ident(v);
2705 read_next_command();
2707 if (skip_prefix(command_buf.buf, "committer ", &v)) {
2708 committer = parse_ident(v);
2709 read_next_command();
2711 if (!committer)
2712 die("Expected committer but didn't get one");
2713 if (skip_prefix(command_buf.buf, "encoding ", &v)) {
2714 encoding = xstrdup(v);
2715 read_next_command();
2717 parse_data(&msg, 0, NULL);
2718 read_next_command();
2719 parse_from(b);
2720 merge_list = parse_merge(&merge_count);
2722 /* ensure the branch is active/loaded */
2723 if (!b->branch_tree.tree || !max_active_branches) {
2724 unload_one_branch();
2725 load_branch(b);
2728 prev_fanout = convert_num_notes_to_fanout(b->num_notes);
2730 /* file_change* */
2731 while (command_buf.len > 0) {
2732 if (skip_prefix(command_buf.buf, "M ", &v))
2733 file_change_m(v, b);
2734 else if (skip_prefix(command_buf.buf, "D ", &v))
2735 file_change_d(v, b);
2736 else if (skip_prefix(command_buf.buf, "R ", &v))
2737 file_change_cr(v, b, 1);
2738 else if (skip_prefix(command_buf.buf, "C ", &v))
2739 file_change_cr(v, b, 0);
2740 else if (skip_prefix(command_buf.buf, "N ", &v))
2741 note_change_n(v, b, &prev_fanout);
2742 else if (!strcmp("deleteall", command_buf.buf))
2743 file_change_deleteall(b);
2744 else if (skip_prefix(command_buf.buf, "ls ", &v))
2745 parse_ls(v, b);
2746 else if (skip_prefix(command_buf.buf, "cat-blob ", &v))
2747 parse_cat_blob(v);
2748 else {
2749 unread_command_buf = 1;
2750 break;
2752 if (read_next_command() == EOF)
2753 break;
2756 new_fanout = convert_num_notes_to_fanout(b->num_notes);
2757 if (new_fanout != prev_fanout)
2758 b->num_notes = change_note_fanout(&b->branch_tree, new_fanout);
2760 /* build the tree and the commit */
2761 store_tree(&b->branch_tree);
2762 oidcpy(&b->branch_tree.versions[0].oid,
2763 &b->branch_tree.versions[1].oid);
2765 strbuf_reset(&new_data);
2766 strbuf_addf(&new_data, "tree %s\n",
2767 oid_to_hex(&b->branch_tree.versions[1].oid));
2768 if (!is_null_oid(&b->oid))
2769 strbuf_addf(&new_data, "parent %s\n",
2770 oid_to_hex(&b->oid));
2771 while (merge_list) {
2772 struct hash_list *next = merge_list->next;
2773 strbuf_addf(&new_data, "parent %s\n",
2774 oid_to_hex(&merge_list->oid));
2775 free(merge_list);
2776 merge_list = next;
2778 strbuf_addf(&new_data,
2779 "author %s\n"
2780 "committer %s\n",
2781 author ? author : committer, committer);
2782 if (encoding)
2783 strbuf_addf(&new_data,
2784 "encoding %s\n",
2785 encoding);
2786 strbuf_addch(&new_data, '\n');
2787 strbuf_addbuf(&new_data, &msg);
2788 free(author);
2789 free(committer);
2790 free(encoding);
2792 if (!store_object(OBJ_COMMIT, &new_data, NULL, &b->oid, next_mark))
2793 b->pack_id = pack_id;
2794 b->last_commit = object_count_by_type[OBJ_COMMIT];
2797 static void parse_new_tag(const char *arg)
2799 static struct strbuf msg = STRBUF_INIT;
2800 const char *from;
2801 char *tagger;
2802 struct branch *s;
2803 struct tag *t;
2804 uintmax_t from_mark = 0;
2805 struct object_id oid;
2806 enum object_type type;
2807 const char *v;
2809 t = mem_pool_alloc(&fi_mem_pool, sizeof(struct tag));
2810 memset(t, 0, sizeof(struct tag));
2811 t->name = mem_pool_strdup(&fi_mem_pool, arg);
2812 if (last_tag)
2813 last_tag->next_tag = t;
2814 else
2815 first_tag = t;
2816 last_tag = t;
2817 read_next_command();
2818 parse_mark();
2820 /* from ... */
2821 if (!skip_prefix(command_buf.buf, "from ", &from))
2822 die("Expected from command, got %s", command_buf.buf);
2823 s = lookup_branch(from);
2824 if (s) {
2825 if (is_null_oid(&s->oid))
2826 die("Can't tag an empty branch.");
2827 oidcpy(&oid, &s->oid);
2828 type = OBJ_COMMIT;
2829 } else if (*from == ':') {
2830 struct object_entry *oe;
2831 from_mark = parse_mark_ref_eol(from);
2832 oe = find_mark(marks, from_mark);
2833 type = oe->type;
2834 oidcpy(&oid, &oe->idx.oid);
2835 } else if (!repo_get_oid(the_repository, from, &oid)) {
2836 struct object_entry *oe = find_object(&oid);
2837 if (!oe) {
2838 type = oid_object_info(the_repository, &oid, NULL);
2839 if (type < 0)
2840 die("Not a valid object: %s", from);
2841 } else
2842 type = oe->type;
2843 } else
2844 die("Invalid ref name or SHA1 expression: %s", from);
2845 read_next_command();
2847 /* original-oid ... */
2848 parse_original_identifier();
2850 /* tagger ... */
2851 if (skip_prefix(command_buf.buf, "tagger ", &v)) {
2852 tagger = parse_ident(v);
2853 read_next_command();
2854 } else
2855 tagger = NULL;
2857 /* tag payload/message */
2858 parse_data(&msg, 0, NULL);
2860 /* build the tag object */
2861 strbuf_reset(&new_data);
2863 strbuf_addf(&new_data,
2864 "object %s\n"
2865 "type %s\n"
2866 "tag %s\n",
2867 oid_to_hex(&oid), type_name(type), t->name);
2868 if (tagger)
2869 strbuf_addf(&new_data,
2870 "tagger %s\n", tagger);
2871 strbuf_addch(&new_data, '\n');
2872 strbuf_addbuf(&new_data, &msg);
2873 free(tagger);
2875 if (store_object(OBJ_TAG, &new_data, NULL, &t->oid, next_mark))
2876 t->pack_id = MAX_PACK_ID;
2877 else
2878 t->pack_id = pack_id;
2881 static void parse_reset_branch(const char *arg)
2883 struct branch *b;
2884 const char *tag_name;
2886 b = lookup_branch(arg);
2887 if (b) {
2888 oidclr(&b->oid);
2889 oidclr(&b->branch_tree.versions[0].oid);
2890 oidclr(&b->branch_tree.versions[1].oid);
2891 if (b->branch_tree.tree) {
2892 release_tree_content_recursive(b->branch_tree.tree);
2893 b->branch_tree.tree = NULL;
2896 else
2897 b = new_branch(arg);
2898 read_next_command();
2899 parse_from(b);
2900 if (b->delete && skip_prefix(b->name, "refs/tags/", &tag_name)) {
2902 * Elsewhere, we call dump_branches() before dump_tags(),
2903 * and dump_branches() will handle ref deletions first, so
2904 * in order to make sure the deletion actually takes effect,
2905 * we need to remove the tag from our list of tags to update.
2907 * NEEDSWORK: replace list of tags with hashmap for faster
2908 * deletion?
2910 struct tag *t, *prev = NULL;
2911 for (t = first_tag; t; t = t->next_tag) {
2912 if (!strcmp(t->name, tag_name))
2913 break;
2914 prev = t;
2916 if (t) {
2917 if (prev)
2918 prev->next_tag = t->next_tag;
2919 else
2920 first_tag = t->next_tag;
2921 if (!t->next_tag)
2922 last_tag = prev;
2923 /* There is no mem_pool_free(t) function to call. */
2926 if (command_buf.len > 0)
2927 unread_command_buf = 1;
2930 static void cat_blob_write(const char *buf, unsigned long size)
2932 if (write_in_full(cat_blob_fd, buf, size) < 0)
2933 die_errno("Write to frontend failed");
2936 static void cat_blob(struct object_entry *oe, struct object_id *oid)
2938 struct strbuf line = STRBUF_INIT;
2939 unsigned long size;
2940 enum object_type type = 0;
2941 char *buf;
2943 if (!oe || oe->pack_id == MAX_PACK_ID) {
2944 buf = repo_read_object_file(the_repository, oid, &type, &size);
2945 } else {
2946 type = oe->type;
2947 buf = gfi_unpack_entry(oe, &size);
2951 * Output based on batch_one_object() from cat-file.c.
2953 if (type <= 0) {
2954 strbuf_reset(&line);
2955 strbuf_addf(&line, "%s missing\n", oid_to_hex(oid));
2956 cat_blob_write(line.buf, line.len);
2957 strbuf_release(&line);
2958 free(buf);
2959 return;
2961 if (!buf)
2962 die("Can't read object %s", oid_to_hex(oid));
2963 if (type != OBJ_BLOB)
2964 die("Object %s is a %s but a blob was expected.",
2965 oid_to_hex(oid), type_name(type));
2966 strbuf_reset(&line);
2967 strbuf_addf(&line, "%s %s %"PRIuMAX"\n", oid_to_hex(oid),
2968 type_name(type), (uintmax_t)size);
2969 cat_blob_write(line.buf, line.len);
2970 strbuf_release(&line);
2971 cat_blob_write(buf, size);
2972 cat_blob_write("\n", 1);
2973 if (oe && oe->pack_id == pack_id) {
2974 last_blob.offset = oe->idx.offset;
2975 strbuf_attach(&last_blob.data, buf, size, size);
2976 last_blob.depth = oe->depth;
2977 } else
2978 free(buf);
2981 static void parse_get_mark(const char *p)
2983 struct object_entry *oe;
2984 char output[GIT_MAX_HEXSZ + 2];
2986 /* get-mark SP <object> LF */
2987 if (*p != ':')
2988 die("Not a mark: %s", p);
2990 oe = find_mark(marks, parse_mark_ref_eol(p));
2991 if (!oe)
2992 die("Unknown mark: %s", command_buf.buf);
2994 xsnprintf(output, sizeof(output), "%s\n", oid_to_hex(&oe->idx.oid));
2995 cat_blob_write(output, the_hash_algo->hexsz + 1);
2998 static void parse_cat_blob(const char *p)
3000 struct object_entry *oe;
3001 struct object_id oid;
3003 /* cat-blob SP <object> LF */
3004 if (*p == ':') {
3005 oe = find_mark(marks, parse_mark_ref_eol(p));
3006 if (!oe)
3007 die("Unknown mark: %s", command_buf.buf);
3008 oidcpy(&oid, &oe->idx.oid);
3009 } else {
3010 if (parse_mapped_oid_hex(p, &oid, &p))
3011 die("Invalid dataref: %s", command_buf.buf);
3012 if (*p)
3013 die("Garbage after SHA1: %s", command_buf.buf);
3014 oe = find_object(&oid);
3017 cat_blob(oe, &oid);
3020 static struct object_entry *dereference(struct object_entry *oe,
3021 struct object_id *oid)
3023 unsigned long size;
3024 char *buf = NULL;
3025 const unsigned hexsz = the_hash_algo->hexsz;
3027 if (!oe) {
3028 enum object_type type = oid_object_info(the_repository, oid,
3029 NULL);
3030 if (type < 0)
3031 die("object not found: %s", oid_to_hex(oid));
3032 /* cache it! */
3033 oe = insert_object(oid);
3034 oe->type = type;
3035 oe->pack_id = MAX_PACK_ID;
3036 oe->idx.offset = 1;
3038 switch (oe->type) {
3039 case OBJ_TREE: /* easy case. */
3040 return oe;
3041 case OBJ_COMMIT:
3042 case OBJ_TAG:
3043 break;
3044 default:
3045 die("Not a tree-ish: %s", command_buf.buf);
3048 if (oe->pack_id != MAX_PACK_ID) { /* in a pack being written */
3049 buf = gfi_unpack_entry(oe, &size);
3050 } else {
3051 enum object_type unused;
3052 buf = repo_read_object_file(the_repository, oid, &unused,
3053 &size);
3055 if (!buf)
3056 die("Can't load object %s", oid_to_hex(oid));
3058 /* Peel one layer. */
3059 switch (oe->type) {
3060 case OBJ_TAG:
3061 if (size < hexsz + strlen("object ") ||
3062 get_oid_hex(buf + strlen("object "), oid))
3063 die("Invalid SHA1 in tag: %s", command_buf.buf);
3064 break;
3065 case OBJ_COMMIT:
3066 if (size < hexsz + strlen("tree ") ||
3067 get_oid_hex(buf + strlen("tree "), oid))
3068 die("Invalid SHA1 in commit: %s", command_buf.buf);
3071 free(buf);
3072 return find_object(oid);
3075 static void insert_mapped_mark(uintmax_t mark, void *object, void *cbp)
3077 struct object_id *fromoid = object;
3078 struct object_id *tooid = find_mark(cbp, mark);
3079 int ret;
3080 khiter_t it;
3082 it = kh_put_oid_map(sub_oid_map, *fromoid, &ret);
3083 /* We've already seen this object. */
3084 if (ret == 0)
3085 return;
3086 kh_value(sub_oid_map, it) = tooid;
3089 static void build_mark_map_one(struct mark_set *from, struct mark_set *to)
3091 for_each_mark(from, 0, insert_mapped_mark, to);
3094 static void build_mark_map(struct string_list *from, struct string_list *to)
3096 struct string_list_item *fromp, *top;
3098 sub_oid_map = kh_init_oid_map();
3100 for_each_string_list_item(fromp, from) {
3101 top = string_list_lookup(to, fromp->string);
3102 if (!fromp->util) {
3103 die(_("Missing from marks for submodule '%s'"), fromp->string);
3104 } else if (!top || !top->util) {
3105 die(_("Missing to marks for submodule '%s'"), fromp->string);
3107 build_mark_map_one(fromp->util, top->util);
3111 static struct object_entry *parse_treeish_dataref(const char **p)
3113 struct object_id oid;
3114 struct object_entry *e;
3116 if (**p == ':') { /* <mark> */
3117 e = find_mark(marks, parse_mark_ref_space(p));
3118 if (!e)
3119 die("Unknown mark: %s", command_buf.buf);
3120 oidcpy(&oid, &e->idx.oid);
3121 } else { /* <sha1> */
3122 if (parse_mapped_oid_hex(*p, &oid, p))
3123 die("Invalid dataref: %s", command_buf.buf);
3124 e = find_object(&oid);
3125 if (*(*p)++ != ' ')
3126 die("Missing space after tree-ish: %s", command_buf.buf);
3129 while (!e || e->type != OBJ_TREE)
3130 e = dereference(e, &oid);
3131 return e;
3134 static void print_ls(int mode, const unsigned char *hash, const char *path)
3136 static struct strbuf line = STRBUF_INIT;
3138 /* See show_tree(). */
3139 const char *type =
3140 S_ISGITLINK(mode) ? commit_type :
3141 S_ISDIR(mode) ? tree_type :
3142 blob_type;
3144 if (!mode) {
3145 /* missing SP path LF */
3146 strbuf_reset(&line);
3147 strbuf_addstr(&line, "missing ");
3148 quote_c_style(path, &line, NULL, 0);
3149 strbuf_addch(&line, '\n');
3150 } else {
3151 /* mode SP type SP object_name TAB path LF */
3152 strbuf_reset(&line);
3153 strbuf_addf(&line, "%06o %s %s\t",
3154 mode & ~NO_DELTA, type, hash_to_hex(hash));
3155 quote_c_style(path, &line, NULL, 0);
3156 strbuf_addch(&line, '\n');
3158 cat_blob_write(line.buf, line.len);
3161 static void parse_ls(const char *p, struct branch *b)
3163 struct tree_entry *root = NULL;
3164 struct tree_entry leaf = {NULL};
3166 /* ls SP (<tree-ish> SP)? <path> */
3167 if (*p == '"') {
3168 if (!b)
3169 die("Not in a commit: %s", command_buf.buf);
3170 root = &b->branch_tree;
3171 } else {
3172 struct object_entry *e = parse_treeish_dataref(&p);
3173 root = new_tree_entry();
3174 oidcpy(&root->versions[1].oid, &e->idx.oid);
3175 if (!is_null_oid(&root->versions[1].oid))
3176 root->versions[1].mode = S_IFDIR;
3177 load_tree(root);
3179 if (*p == '"') {
3180 static struct strbuf uq = STRBUF_INIT;
3181 const char *endp;
3182 strbuf_reset(&uq);
3183 if (unquote_c_style(&uq, p, &endp))
3184 die("Invalid path: %s", command_buf.buf);
3185 if (*endp)
3186 die("Garbage after path in: %s", command_buf.buf);
3187 p = uq.buf;
3189 tree_content_get(root, p, &leaf, 1);
3191 * A directory in preparation would have a sha1 of zero
3192 * until it is saved. Save, for simplicity.
3194 if (S_ISDIR(leaf.versions[1].mode))
3195 store_tree(&leaf);
3197 print_ls(leaf.versions[1].mode, leaf.versions[1].oid.hash, p);
3198 if (leaf.tree)
3199 release_tree_content_recursive(leaf.tree);
3200 if (!b || root != &b->branch_tree)
3201 release_tree_entry(root);
3204 static void checkpoint(void)
3206 checkpoint_requested = 0;
3207 if (object_count) {
3208 cycle_packfile();
3210 dump_branches();
3211 dump_tags();
3212 dump_marks();
3215 static void parse_checkpoint(void)
3217 checkpoint_requested = 1;
3218 skip_optional_lf();
3221 static void parse_progress(void)
3223 fwrite(command_buf.buf, 1, command_buf.len, stdout);
3224 fputc('\n', stdout);
3225 fflush(stdout);
3226 skip_optional_lf();
3229 static void parse_alias(void)
3231 struct object_entry *e;
3232 struct branch b;
3234 skip_optional_lf();
3235 read_next_command();
3237 /* mark ... */
3238 parse_mark();
3239 if (!next_mark)
3240 die(_("Expected 'mark' command, got %s"), command_buf.buf);
3242 /* to ... */
3243 memset(&b, 0, sizeof(b));
3244 if (!parse_objectish_with_prefix(&b, "to "))
3245 die(_("Expected 'to' command, got %s"), command_buf.buf);
3246 e = find_object(&b.oid);
3247 assert(e);
3248 insert_mark(&marks, next_mark, e);
3251 static char* make_fast_import_path(const char *path)
3253 if (!relative_marks_paths || is_absolute_path(path))
3254 return xstrdup(path);
3255 return git_pathdup("info/fast-import/%s", path);
3258 static void option_import_marks(const char *marks,
3259 int from_stream, int ignore_missing)
3261 if (import_marks_file) {
3262 if (from_stream)
3263 die("Only one import-marks command allowed per stream");
3265 /* read previous mark file */
3266 if(!import_marks_file_from_stream)
3267 read_marks();
3270 import_marks_file = make_fast_import_path(marks);
3271 import_marks_file_from_stream = from_stream;
3272 import_marks_file_ignore_missing = ignore_missing;
3275 static void option_date_format(const char *fmt)
3277 if (!strcmp(fmt, "raw"))
3278 whenspec = WHENSPEC_RAW;
3279 else if (!strcmp(fmt, "raw-permissive"))
3280 whenspec = WHENSPEC_RAW_PERMISSIVE;
3281 else if (!strcmp(fmt, "rfc2822"))
3282 whenspec = WHENSPEC_RFC2822;
3283 else if (!strcmp(fmt, "now"))
3284 whenspec = WHENSPEC_NOW;
3285 else
3286 die("unknown --date-format argument %s", fmt);
3289 static unsigned long ulong_arg(const char *option, const char *arg)
3291 char *endptr;
3292 unsigned long rv = strtoul(arg, &endptr, 0);
3293 if (strchr(arg, '-') || endptr == arg || *endptr)
3294 die("%s: argument must be a non-negative integer", option);
3295 return rv;
3298 static void option_depth(const char *depth)
3300 max_depth = ulong_arg("--depth", depth);
3301 if (max_depth > MAX_DEPTH)
3302 die("--depth cannot exceed %u", MAX_DEPTH);
3305 static void option_active_branches(const char *branches)
3307 max_active_branches = ulong_arg("--active-branches", branches);
3310 static void option_export_marks(const char *marks)
3312 export_marks_file = make_fast_import_path(marks);
3315 static void option_cat_blob_fd(const char *fd)
3317 unsigned long n = ulong_arg("--cat-blob-fd", fd);
3318 if (n > (unsigned long) INT_MAX)
3319 die("--cat-blob-fd cannot exceed %d", INT_MAX);
3320 cat_blob_fd = (int) n;
3323 static void option_export_pack_edges(const char *edges)
3325 if (pack_edges)
3326 fclose(pack_edges);
3327 pack_edges = xfopen(edges, "a");
3330 static void option_rewrite_submodules(const char *arg, struct string_list *list)
3332 struct mark_set *ms;
3333 FILE *fp;
3334 char *s = xstrdup(arg);
3335 char *f = strchr(s, ':');
3336 if (!f)
3337 die(_("Expected format name:filename for submodule rewrite option"));
3338 *f = '\0';
3339 f++;
3340 CALLOC_ARRAY(ms, 1);
3342 fp = fopen(f, "r");
3343 if (!fp)
3344 die_errno("cannot read '%s'", f);
3345 read_mark_file(&ms, fp, insert_oid_entry);
3346 fclose(fp);
3348 string_list_insert(list, s)->util = ms;
3351 static int parse_one_option(const char *option)
3353 if (skip_prefix(option, "max-pack-size=", &option)) {
3354 unsigned long v;
3355 if (!git_parse_ulong(option, &v))
3356 return 0;
3357 if (v < 8192) {
3358 warning("max-pack-size is now in bytes, assuming --max-pack-size=%lum", v);
3359 v *= 1024 * 1024;
3360 } else if (v < 1024 * 1024) {
3361 warning("minimum max-pack-size is 1 MiB");
3362 v = 1024 * 1024;
3364 max_packsize = v;
3365 } else if (skip_prefix(option, "big-file-threshold=", &option)) {
3366 unsigned long v;
3367 if (!git_parse_ulong(option, &v))
3368 return 0;
3369 big_file_threshold = v;
3370 } else if (skip_prefix(option, "depth=", &option)) {
3371 option_depth(option);
3372 } else if (skip_prefix(option, "active-branches=", &option)) {
3373 option_active_branches(option);
3374 } else if (skip_prefix(option, "export-pack-edges=", &option)) {
3375 option_export_pack_edges(option);
3376 } else if (!strcmp(option, "quiet")) {
3377 show_stats = 0;
3378 } else if (!strcmp(option, "stats")) {
3379 show_stats = 1;
3380 } else if (!strcmp(option, "allow-unsafe-features")) {
3381 ; /* already handled during early option parsing */
3382 } else {
3383 return 0;
3386 return 1;
3389 static void check_unsafe_feature(const char *feature, int from_stream)
3391 if (from_stream && !allow_unsafe_features)
3392 die(_("feature '%s' forbidden in input without --allow-unsafe-features"),
3393 feature);
3396 static int parse_one_feature(const char *feature, int from_stream)
3398 const char *arg;
3400 if (skip_prefix(feature, "date-format=", &arg)) {
3401 option_date_format(arg);
3402 } else if (skip_prefix(feature, "import-marks=", &arg)) {
3403 check_unsafe_feature("import-marks", from_stream);
3404 option_import_marks(arg, from_stream, 0);
3405 } else if (skip_prefix(feature, "import-marks-if-exists=", &arg)) {
3406 check_unsafe_feature("import-marks-if-exists", from_stream);
3407 option_import_marks(arg, from_stream, 1);
3408 } else if (skip_prefix(feature, "export-marks=", &arg)) {
3409 check_unsafe_feature(feature, from_stream);
3410 option_export_marks(arg);
3411 } else if (!strcmp(feature, "alias")) {
3412 ; /* Don't die - this feature is supported */
3413 } else if (skip_prefix(feature, "rewrite-submodules-to=", &arg)) {
3414 option_rewrite_submodules(arg, &sub_marks_to);
3415 } else if (skip_prefix(feature, "rewrite-submodules-from=", &arg)) {
3416 option_rewrite_submodules(arg, &sub_marks_from);
3417 } else if (!strcmp(feature, "get-mark")) {
3418 ; /* Don't die - this feature is supported */
3419 } else if (!strcmp(feature, "cat-blob")) {
3420 ; /* Don't die - this feature is supported */
3421 } else if (!strcmp(feature, "relative-marks")) {
3422 relative_marks_paths = 1;
3423 } else if (!strcmp(feature, "no-relative-marks")) {
3424 relative_marks_paths = 0;
3425 } else if (!strcmp(feature, "done")) {
3426 require_explicit_termination = 1;
3427 } else if (!strcmp(feature, "force")) {
3428 force_update = 1;
3429 } else if (!strcmp(feature, "notes") || !strcmp(feature, "ls")) {
3430 ; /* do nothing; we have the feature */
3431 } else {
3432 return 0;
3435 return 1;
3438 static void parse_feature(const char *feature)
3440 if (seen_data_command)
3441 die("Got feature command '%s' after data command", feature);
3443 if (parse_one_feature(feature, 1))
3444 return;
3446 die("This version of fast-import does not support feature %s.", feature);
3449 static void parse_option(const char *option)
3451 if (seen_data_command)
3452 die("Got option command '%s' after data command", option);
3454 if (parse_one_option(option))
3455 return;
3457 die("This version of fast-import does not support option: %s", option);
3460 static void git_pack_config(void)
3462 int indexversion_value;
3463 int limit;
3464 unsigned long packsizelimit_value;
3466 if (!git_config_get_ulong("pack.depth", &max_depth)) {
3467 if (max_depth > MAX_DEPTH)
3468 max_depth = MAX_DEPTH;
3470 if (!git_config_get_int("pack.indexversion", &indexversion_value)) {
3471 pack_idx_opts.version = indexversion_value;
3472 if (pack_idx_opts.version > 2)
3473 git_die_config("pack.indexversion",
3474 "bad pack.indexVersion=%"PRIu32, pack_idx_opts.version);
3476 if (!git_config_get_ulong("pack.packsizelimit", &packsizelimit_value))
3477 max_packsize = packsizelimit_value;
3479 if (!git_config_get_int("fastimport.unpacklimit", &limit))
3480 unpack_limit = limit;
3481 else if (!git_config_get_int("transfer.unpacklimit", &limit))
3482 unpack_limit = limit;
3484 git_config(git_default_config, NULL);
3487 static const char fast_import_usage[] =
3488 "git fast-import [--date-format=<f>] [--max-pack-size=<n>] [--big-file-threshold=<n>] [--depth=<n>] [--active-branches=<n>] [--export-marks=<marks.file>]";
3490 static void parse_argv(void)
3492 unsigned int i;
3494 for (i = 1; i < global_argc; i++) {
3495 const char *a = global_argv[i];
3497 if (*a != '-' || !strcmp(a, "--"))
3498 break;
3500 if (!skip_prefix(a, "--", &a))
3501 die("unknown option %s", a);
3503 if (parse_one_option(a))
3504 continue;
3506 if (parse_one_feature(a, 0))
3507 continue;
3509 if (skip_prefix(a, "cat-blob-fd=", &a)) {
3510 option_cat_blob_fd(a);
3511 continue;
3514 die("unknown option --%s", a);
3516 if (i != global_argc)
3517 usage(fast_import_usage);
3519 seen_data_command = 1;
3520 if (import_marks_file)
3521 read_marks();
3522 build_mark_map(&sub_marks_from, &sub_marks_to);
3525 int cmd_fast_import(int argc, const char **argv, const char *prefix)
3527 unsigned int i;
3529 if (argc == 2 && !strcmp(argv[1], "-h"))
3530 usage(fast_import_usage);
3532 reset_pack_idx_option(&pack_idx_opts);
3533 git_pack_config();
3535 alloc_objects(object_entry_alloc);
3536 strbuf_init(&command_buf, 0);
3537 CALLOC_ARRAY(atom_table, atom_table_sz);
3538 CALLOC_ARRAY(branch_table, branch_table_sz);
3539 CALLOC_ARRAY(avail_tree_table, avail_tree_table_sz);
3540 marks = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
3542 hashmap_init(&object_table, object_entry_hashcmp, NULL, 0);
3545 * We don't parse most options until after we've seen the set of
3546 * "feature" lines at the start of the stream (which allows the command
3547 * line to override stream data). But we must do an early parse of any
3548 * command-line options that impact how we interpret the feature lines.
3550 for (i = 1; i < argc; i++) {
3551 const char *arg = argv[i];
3552 if (*arg != '-' || !strcmp(arg, "--"))
3553 break;
3554 if (!strcmp(arg, "--allow-unsafe-features"))
3555 allow_unsafe_features = 1;
3558 global_argc = argc;
3559 global_argv = argv;
3561 rc_free = mem_pool_alloc(&fi_mem_pool, cmd_save * sizeof(*rc_free));
3562 for (i = 0; i < (cmd_save - 1); i++)
3563 rc_free[i].next = &rc_free[i + 1];
3564 rc_free[cmd_save - 1].next = NULL;
3566 start_packfile();
3567 set_die_routine(die_nicely);
3568 set_checkpoint_signal();
3569 while (read_next_command() != EOF) {
3570 const char *v;
3571 if (!strcmp("blob", command_buf.buf))
3572 parse_new_blob();
3573 else if (skip_prefix(command_buf.buf, "commit ", &v))
3574 parse_new_commit(v);
3575 else if (skip_prefix(command_buf.buf, "tag ", &v))
3576 parse_new_tag(v);
3577 else if (skip_prefix(command_buf.buf, "reset ", &v))
3578 parse_reset_branch(v);
3579 else if (skip_prefix(command_buf.buf, "ls ", &v))
3580 parse_ls(v, NULL);
3581 else if (skip_prefix(command_buf.buf, "cat-blob ", &v))
3582 parse_cat_blob(v);
3583 else if (skip_prefix(command_buf.buf, "get-mark ", &v))
3584 parse_get_mark(v);
3585 else if (!strcmp("checkpoint", command_buf.buf))
3586 parse_checkpoint();
3587 else if (!strcmp("done", command_buf.buf))
3588 break;
3589 else if (!strcmp("alias", command_buf.buf))
3590 parse_alias();
3591 else if (starts_with(command_buf.buf, "progress "))
3592 parse_progress();
3593 else if (skip_prefix(command_buf.buf, "feature ", &v))
3594 parse_feature(v);
3595 else if (skip_prefix(command_buf.buf, "option git ", &v))
3596 parse_option(v);
3597 else if (starts_with(command_buf.buf, "option "))
3598 /* ignore non-git options*/;
3599 else
3600 die("Unsupported command: %s", command_buf.buf);
3602 if (checkpoint_requested)
3603 checkpoint();
3606 /* argv hasn't been parsed yet, do so */
3607 if (!seen_data_command)
3608 parse_argv();
3610 if (require_explicit_termination && feof(stdin))
3611 die("stream ends early");
3613 end_packfile();
3615 dump_branches();
3616 dump_tags();
3617 unkeep_all_packs();
3618 dump_marks();
3620 if (pack_edges)
3621 fclose(pack_edges);
3623 if (show_stats) {
3624 uintmax_t total_count = 0, duplicate_count = 0;
3625 for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
3626 total_count += object_count_by_type[i];
3627 for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
3628 duplicate_count += duplicate_count_by_type[i];
3630 fprintf(stderr, "%s statistics:\n", argv[0]);
3631 fprintf(stderr, "---------------------------------------------------------------------\n");
3632 fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
3633 fprintf(stderr, "Total objects: %10" PRIuMAX " (%10" PRIuMAX " duplicates )\n", total_count, duplicate_count);
3634 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]);
3635 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]);
3636 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]);
3637 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]);
3638 fprintf(stderr, "Total branches: %10lu (%10lu loads )\n", branch_count, branch_load_count);
3639 fprintf(stderr, " marks: %10" PRIuMAX " (%10" PRIuMAX " unique )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
3640 fprintf(stderr, " atoms: %10u\n", atom_cnt);
3641 fprintf(stderr, "Memory total: %10" PRIuMAX " KiB\n", (tree_entry_allocd + fi_mem_pool.pool_alloc + alloc_count*sizeof(struct object_entry))/1024);
3642 fprintf(stderr, " pools: %10lu KiB\n", (unsigned long)((tree_entry_allocd + fi_mem_pool.pool_alloc) /1024));
3643 fprintf(stderr, " objects: %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
3644 fprintf(stderr, "---------------------------------------------------------------------\n");
3645 pack_report();
3646 fprintf(stderr, "---------------------------------------------------------------------\n");
3647 fprintf(stderr, "\n");
3650 return failure ? 1 : 0;