ls-remote & transport API: release "struct transport_ls_refs_options"
[git/debian.git] / builtin / fast-import.c
blob2b2e28bad79cbaef25b4eb8fea4c0f800ba4a89d
1 #include "builtin.h"
2 #include "cache.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "lockfile.h"
6 #include "object.h"
7 #include "blob.h"
8 #include "tree.h"
9 #include "commit.h"
10 #include "delta.h"
11 #include "pack.h"
12 #include "refs.h"
13 #include "csum-file.h"
14 #include "quote.h"
15 #include "dir.h"
16 #include "run-command.h"
17 #include "packfile.h"
18 #include "object-store.h"
19 #include "mem-pool.h"
20 #include "commit-reach.h"
21 #include "khash.h"
23 #define PACK_ID_BITS 16
24 #define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
25 #define DEPTH_BITS 13
26 #define MAX_DEPTH ((1<<DEPTH_BITS)-1)
29 * We abuse the setuid bit on directories to mean "do not delta".
31 #define NO_DELTA S_ISUID
34 * The amount of additional space required in order to write an object into the
35 * current pack. This is the hash lengths at the end of the pack, plus the
36 * length of one object ID.
38 #define PACK_SIZE_THRESHOLD (the_hash_algo->rawsz * 3)
40 struct object_entry {
41 struct pack_idx_entry idx;
42 struct hashmap_entry ent;
43 uint32_t type : TYPE_BITS,
44 pack_id : PACK_ID_BITS,
45 depth : DEPTH_BITS;
48 static int object_entry_hashcmp(const void *map_data,
49 const struct hashmap_entry *eptr,
50 const struct hashmap_entry *entry_or_key,
51 const void *keydata)
53 const struct object_id *oid = keydata;
54 const struct object_entry *e1, *e2;
56 e1 = container_of(eptr, const struct object_entry, ent);
57 if (oid)
58 return oidcmp(&e1->idx.oid, oid);
60 e2 = container_of(entry_or_key, const struct object_entry, ent);
61 return oidcmp(&e1->idx.oid, &e2->idx.oid);
64 struct object_entry_pool {
65 struct object_entry_pool *next_pool;
66 struct object_entry *next_free;
67 struct object_entry *end;
68 struct object_entry entries[FLEX_ARRAY]; /* more */
71 struct mark_set {
72 union {
73 struct object_id *oids[1024];
74 struct object_entry *marked[1024];
75 struct mark_set *sets[1024];
76 } data;
77 unsigned int shift;
80 struct last_object {
81 struct strbuf data;
82 off_t offset;
83 unsigned int depth;
84 unsigned no_swap : 1;
87 struct atom_str {
88 struct atom_str *next_atom;
89 unsigned short str_len;
90 char str_dat[FLEX_ARRAY]; /* more */
93 struct tree_content;
94 struct tree_entry {
95 struct tree_content *tree;
96 struct atom_str *name;
97 struct tree_entry_ms {
98 uint16_t mode;
99 struct object_id oid;
100 } versions[2];
103 struct tree_content {
104 unsigned int entry_capacity; /* must match avail_tree_content */
105 unsigned int entry_count;
106 unsigned int delta_depth;
107 struct tree_entry *entries[FLEX_ARRAY]; /* more */
110 struct avail_tree_content {
111 unsigned int entry_capacity; /* must match tree_content */
112 struct avail_tree_content *next_avail;
115 struct branch {
116 struct branch *table_next_branch;
117 struct branch *active_next_branch;
118 const char *name;
119 struct tree_entry branch_tree;
120 uintmax_t last_commit;
121 uintmax_t num_notes;
122 unsigned active : 1;
123 unsigned delete : 1;
124 unsigned pack_id : PACK_ID_BITS;
125 struct object_id oid;
128 struct tag {
129 struct tag *next_tag;
130 const char *name;
131 unsigned int pack_id;
132 struct object_id oid;
135 struct hash_list {
136 struct hash_list *next;
137 struct object_id oid;
140 typedef enum {
141 WHENSPEC_RAW = 1,
142 WHENSPEC_RAW_PERMISSIVE,
143 WHENSPEC_RFC2822,
144 WHENSPEC_NOW
145 } whenspec_type;
147 struct recent_command {
148 struct recent_command *prev;
149 struct recent_command *next;
150 char *buf;
153 typedef void (*mark_set_inserter_t)(struct mark_set **s, struct object_id *oid, uintmax_t mark);
154 typedef void (*each_mark_fn_t)(uintmax_t mark, void *obj, void *cbp);
156 /* Configured limits on output */
157 static unsigned long max_depth = 50;
158 static off_t max_packsize;
159 static int unpack_limit = 100;
160 static int force_update;
162 /* Stats and misc. counters */
163 static uintmax_t alloc_count;
164 static uintmax_t marks_set_count;
165 static uintmax_t object_count_by_type[1 << TYPE_BITS];
166 static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
167 static uintmax_t delta_count_by_type[1 << TYPE_BITS];
168 static uintmax_t delta_count_attempts_by_type[1 << TYPE_BITS];
169 static unsigned long object_count;
170 static unsigned long branch_count;
171 static unsigned long branch_load_count;
172 static int failure;
173 static FILE *pack_edges;
174 static unsigned int show_stats = 1;
175 static int global_argc;
176 static const char **global_argv;
178 /* Memory pools */
179 static struct mem_pool fi_mem_pool = {NULL, 2*1024*1024 -
180 sizeof(struct mp_block), 0 };
182 /* Atom management */
183 static unsigned int atom_table_sz = 4451;
184 static unsigned int atom_cnt;
185 static struct atom_str **atom_table;
187 /* The .pack file being generated */
188 static struct pack_idx_option pack_idx_opts;
189 static unsigned int pack_id;
190 static struct hashfile *pack_file;
191 static struct packed_git *pack_data;
192 static struct packed_git **all_packs;
193 static off_t pack_size;
195 /* Table of objects we've written. */
196 static unsigned int object_entry_alloc = 5000;
197 static struct object_entry_pool *blocks;
198 static struct hashmap object_table;
199 static struct mark_set *marks;
200 static const char *export_marks_file;
201 static const char *import_marks_file;
202 static int import_marks_file_from_stream;
203 static int import_marks_file_ignore_missing;
204 static int import_marks_file_done;
205 static int relative_marks_paths;
207 /* Our last blob */
208 static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
210 /* Tree management */
211 static unsigned int tree_entry_alloc = 1000;
212 static void *avail_tree_entry;
213 static unsigned int avail_tree_table_sz = 100;
214 static struct avail_tree_content **avail_tree_table;
215 static size_t tree_entry_allocd;
216 static struct strbuf old_tree = STRBUF_INIT;
217 static struct strbuf new_tree = STRBUF_INIT;
219 /* Branch data */
220 static unsigned long max_active_branches = 5;
221 static unsigned long cur_active_branches;
222 static unsigned long branch_table_sz = 1039;
223 static struct branch **branch_table;
224 static struct branch *active_branches;
226 /* Tag data */
227 static struct tag *first_tag;
228 static struct tag *last_tag;
230 /* Input stream parsing */
231 static whenspec_type whenspec = WHENSPEC_RAW;
232 static struct strbuf command_buf = STRBUF_INIT;
233 static int unread_command_buf;
234 static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
235 static struct recent_command *cmd_tail = &cmd_hist;
236 static struct recent_command *rc_free;
237 static unsigned int cmd_save = 100;
238 static uintmax_t next_mark;
239 static struct strbuf new_data = STRBUF_INIT;
240 static int seen_data_command;
241 static int require_explicit_termination;
242 static int allow_unsafe_features;
244 /* Signal handling */
245 static volatile sig_atomic_t checkpoint_requested;
247 /* Submodule marks */
248 static struct string_list sub_marks_from = STRING_LIST_INIT_DUP;
249 static struct string_list sub_marks_to = STRING_LIST_INIT_DUP;
250 static kh_oid_map_t *sub_oid_map;
252 /* Where to write output of cat-blob commands */
253 static int cat_blob_fd = STDOUT_FILENO;
255 static void parse_argv(void);
256 static void parse_get_mark(const char *p);
257 static void parse_cat_blob(const char *p);
258 static void parse_ls(const char *p, struct branch *b);
260 static void for_each_mark(struct mark_set *m, uintmax_t base, each_mark_fn_t callback, void *p)
262 uintmax_t k;
263 if (m->shift) {
264 for (k = 0; k < 1024; k++) {
265 if (m->data.sets[k])
266 for_each_mark(m->data.sets[k], base + (k << m->shift), callback, p);
268 } else {
269 for (k = 0; k < 1024; k++) {
270 if (m->data.marked[k])
271 callback(base + k, m->data.marked[k], p);
276 static void dump_marks_fn(uintmax_t mark, void *object, void *cbp) {
277 struct object_entry *e = object;
278 FILE *f = cbp;
280 fprintf(f, ":%" PRIuMAX " %s\n", mark, oid_to_hex(&e->idx.oid));
283 static void write_branch_report(FILE *rpt, struct branch *b)
285 fprintf(rpt, "%s:\n", b->name);
287 fprintf(rpt, " status :");
288 if (b->active)
289 fputs(" active", rpt);
290 if (b->branch_tree.tree)
291 fputs(" loaded", rpt);
292 if (is_null_oid(&b->branch_tree.versions[1].oid))
293 fputs(" dirty", rpt);
294 fputc('\n', rpt);
296 fprintf(rpt, " tip commit : %s\n", oid_to_hex(&b->oid));
297 fprintf(rpt, " old tree : %s\n",
298 oid_to_hex(&b->branch_tree.versions[0].oid));
299 fprintf(rpt, " cur tree : %s\n",
300 oid_to_hex(&b->branch_tree.versions[1].oid));
301 fprintf(rpt, " commit clock: %" PRIuMAX "\n", b->last_commit);
303 fputs(" last pack : ", rpt);
304 if (b->pack_id < MAX_PACK_ID)
305 fprintf(rpt, "%u", b->pack_id);
306 fputc('\n', rpt);
308 fputc('\n', rpt);
311 static void write_crash_report(const char *err)
313 char *loc = git_pathdup("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
314 FILE *rpt = fopen(loc, "w");
315 struct branch *b;
316 unsigned long lu;
317 struct recent_command *rc;
319 if (!rpt) {
320 error_errno("can't write crash report %s", loc);
321 free(loc);
322 return;
325 fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
327 fprintf(rpt, "fast-import crash report:\n");
328 fprintf(rpt, " fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
329 fprintf(rpt, " parent process : %"PRIuMAX"\n", (uintmax_t) getppid());
330 fprintf(rpt, " at %s\n", show_date(time(NULL), 0, DATE_MODE(ISO8601)));
331 fputc('\n', rpt);
333 fputs("fatal: ", rpt);
334 fputs(err, rpt);
335 fputc('\n', rpt);
337 fputc('\n', rpt);
338 fputs("Most Recent Commands Before Crash\n", rpt);
339 fputs("---------------------------------\n", rpt);
340 for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
341 if (rc->next == &cmd_hist)
342 fputs("* ", rpt);
343 else
344 fputs(" ", rpt);
345 fputs(rc->buf, rpt);
346 fputc('\n', rpt);
349 fputc('\n', rpt);
350 fputs("Active Branch LRU\n", rpt);
351 fputs("-----------------\n", rpt);
352 fprintf(rpt, " active_branches = %lu cur, %lu max\n",
353 cur_active_branches,
354 max_active_branches);
355 fputc('\n', rpt);
356 fputs(" pos clock name\n", rpt);
357 fputs(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
358 for (b = active_branches, lu = 0; b; b = b->active_next_branch)
359 fprintf(rpt, " %2lu) %6" PRIuMAX" %s\n",
360 ++lu, b->last_commit, b->name);
362 fputc('\n', rpt);
363 fputs("Inactive Branches\n", rpt);
364 fputs("-----------------\n", rpt);
365 for (lu = 0; lu < branch_table_sz; lu++) {
366 for (b = branch_table[lu]; b; b = b->table_next_branch)
367 write_branch_report(rpt, b);
370 if (first_tag) {
371 struct tag *tg;
372 fputc('\n', rpt);
373 fputs("Annotated Tags\n", rpt);
374 fputs("--------------\n", rpt);
375 for (tg = first_tag; tg; tg = tg->next_tag) {
376 fputs(oid_to_hex(&tg->oid), rpt);
377 fputc(' ', rpt);
378 fputs(tg->name, rpt);
379 fputc('\n', rpt);
383 fputc('\n', rpt);
384 fputs("Marks\n", rpt);
385 fputs("-----\n", rpt);
386 if (export_marks_file)
387 fprintf(rpt, " exported to %s\n", export_marks_file);
388 else
389 for_each_mark(marks, 0, dump_marks_fn, rpt);
391 fputc('\n', rpt);
392 fputs("-------------------\n", rpt);
393 fputs("END OF CRASH REPORT\n", rpt);
394 fclose(rpt);
395 free(loc);
398 static void end_packfile(void);
399 static void unkeep_all_packs(void);
400 static void dump_marks(void);
402 static NORETURN void die_nicely(const char *err, va_list params)
404 va_list cp;
405 static int zombie;
406 report_fn die_message_fn = get_die_message_routine();
408 va_copy(cp, params);
409 die_message_fn(err, params);
411 if (!zombie) {
412 char message[2 * PATH_MAX];
414 zombie = 1;
415 vsnprintf(message, sizeof(message), err, cp);
416 write_crash_report(message);
417 end_packfile();
418 unkeep_all_packs();
419 dump_marks();
421 exit(128);
424 #ifndef SIGUSR1 /* Windows, for example */
426 static void set_checkpoint_signal(void)
430 #else
432 static void checkpoint_signal(int signo)
434 checkpoint_requested = 1;
437 static void set_checkpoint_signal(void)
439 struct sigaction sa;
441 memset(&sa, 0, sizeof(sa));
442 sa.sa_handler = checkpoint_signal;
443 sigemptyset(&sa.sa_mask);
444 sa.sa_flags = SA_RESTART;
445 sigaction(SIGUSR1, &sa, NULL);
448 #endif
450 static void alloc_objects(unsigned int cnt)
452 struct object_entry_pool *b;
454 b = xmalloc(sizeof(struct object_entry_pool)
455 + cnt * sizeof(struct object_entry));
456 b->next_pool = blocks;
457 b->next_free = b->entries;
458 b->end = b->entries + cnt;
459 blocks = b;
460 alloc_count += cnt;
463 static struct object_entry *new_object(struct object_id *oid)
465 struct object_entry *e;
467 if (blocks->next_free == blocks->end)
468 alloc_objects(object_entry_alloc);
470 e = blocks->next_free++;
471 oidcpy(&e->idx.oid, oid);
472 return e;
475 static struct object_entry *find_object(struct object_id *oid)
477 return hashmap_get_entry_from_hash(&object_table, oidhash(oid), oid,
478 struct object_entry, ent);
481 static struct object_entry *insert_object(struct object_id *oid)
483 struct object_entry *e;
484 unsigned int hash = oidhash(oid);
486 e = hashmap_get_entry_from_hash(&object_table, hash, oid,
487 struct object_entry, ent);
488 if (!e) {
489 e = new_object(oid);
490 e->idx.offset = 0;
491 hashmap_entry_init(&e->ent, hash);
492 hashmap_add(&object_table, &e->ent);
495 return e;
498 static void invalidate_pack_id(unsigned int id)
500 unsigned long lu;
501 struct tag *t;
502 struct hashmap_iter iter;
503 struct object_entry *e;
505 hashmap_for_each_entry(&object_table, &iter, e, ent) {
506 if (e->pack_id == id)
507 e->pack_id = MAX_PACK_ID;
510 for (lu = 0; lu < branch_table_sz; lu++) {
511 struct branch *b;
513 for (b = branch_table[lu]; b; b = b->table_next_branch)
514 if (b->pack_id == id)
515 b->pack_id = MAX_PACK_ID;
518 for (t = first_tag; t; t = t->next_tag)
519 if (t->pack_id == id)
520 t->pack_id = MAX_PACK_ID;
523 static unsigned int hc_str(const char *s, size_t len)
525 unsigned int r = 0;
526 while (len-- > 0)
527 r = r * 31 + *s++;
528 return r;
531 static void insert_mark(struct mark_set **top, uintmax_t idnum, struct object_entry *oe)
533 struct mark_set *s = *top;
535 while ((idnum >> s->shift) >= 1024) {
536 s = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
537 s->shift = (*top)->shift + 10;
538 s->data.sets[0] = *top;
539 *top = s;
541 while (s->shift) {
542 uintmax_t i = idnum >> s->shift;
543 idnum -= i << s->shift;
544 if (!s->data.sets[i]) {
545 s->data.sets[i] = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
546 s->data.sets[i]->shift = s->shift - 10;
548 s = s->data.sets[i];
550 if (!s->data.marked[idnum])
551 marks_set_count++;
552 s->data.marked[idnum] = oe;
555 static void *find_mark(struct mark_set *s, uintmax_t idnum)
557 uintmax_t orig_idnum = idnum;
558 struct object_entry *oe = NULL;
559 if ((idnum >> s->shift) < 1024) {
560 while (s && s->shift) {
561 uintmax_t i = idnum >> s->shift;
562 idnum -= i << s->shift;
563 s = s->data.sets[i];
565 if (s)
566 oe = s->data.marked[idnum];
568 if (!oe)
569 die("mark :%" PRIuMAX " not declared", orig_idnum);
570 return oe;
573 static struct atom_str *to_atom(const char *s, unsigned short len)
575 unsigned int hc = hc_str(s, len) % atom_table_sz;
576 struct atom_str *c;
578 for (c = atom_table[hc]; c; c = c->next_atom)
579 if (c->str_len == len && !strncmp(s, c->str_dat, len))
580 return c;
582 c = mem_pool_alloc(&fi_mem_pool, sizeof(struct atom_str) + len + 1);
583 c->str_len = len;
584 memcpy(c->str_dat, s, len);
585 c->str_dat[len] = 0;
586 c->next_atom = atom_table[hc];
587 atom_table[hc] = c;
588 atom_cnt++;
589 return c;
592 static struct branch *lookup_branch(const char *name)
594 unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
595 struct branch *b;
597 for (b = branch_table[hc]; b; b = b->table_next_branch)
598 if (!strcmp(name, b->name))
599 return b;
600 return NULL;
603 static struct branch *new_branch(const char *name)
605 unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
606 struct branch *b = lookup_branch(name);
608 if (b)
609 die("Invalid attempt to create duplicate branch: %s", name);
610 if (check_refname_format(name, REFNAME_ALLOW_ONELEVEL))
611 die("Branch name doesn't conform to GIT standards: %s", name);
613 b = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct branch));
614 b->name = mem_pool_strdup(&fi_mem_pool, name);
615 b->table_next_branch = branch_table[hc];
616 b->branch_tree.versions[0].mode = S_IFDIR;
617 b->branch_tree.versions[1].mode = S_IFDIR;
618 b->num_notes = 0;
619 b->active = 0;
620 b->pack_id = MAX_PACK_ID;
621 branch_table[hc] = b;
622 branch_count++;
623 return b;
626 static unsigned int hc_entries(unsigned int cnt)
628 cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
629 return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
632 static struct tree_content *new_tree_content(unsigned int cnt)
634 struct avail_tree_content *f, *l = NULL;
635 struct tree_content *t;
636 unsigned int hc = hc_entries(cnt);
638 for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
639 if (f->entry_capacity >= cnt)
640 break;
642 if (f) {
643 if (l)
644 l->next_avail = f->next_avail;
645 else
646 avail_tree_table[hc] = f->next_avail;
647 } else {
648 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
649 f = mem_pool_alloc(&fi_mem_pool, sizeof(*t) + sizeof(t->entries[0]) * cnt);
650 f->entry_capacity = cnt;
653 t = (struct tree_content*)f;
654 t->entry_count = 0;
655 t->delta_depth = 0;
656 return t;
659 static void release_tree_entry(struct tree_entry *e);
660 static void release_tree_content(struct tree_content *t)
662 struct avail_tree_content *f = (struct avail_tree_content*)t;
663 unsigned int hc = hc_entries(f->entry_capacity);
664 f->next_avail = avail_tree_table[hc];
665 avail_tree_table[hc] = f;
668 static void release_tree_content_recursive(struct tree_content *t)
670 unsigned int i;
671 for (i = 0; i < t->entry_count; i++)
672 release_tree_entry(t->entries[i]);
673 release_tree_content(t);
676 static struct tree_content *grow_tree_content(
677 struct tree_content *t,
678 int amt)
680 struct tree_content *r = new_tree_content(t->entry_count + amt);
681 r->entry_count = t->entry_count;
682 r->delta_depth = t->delta_depth;
683 COPY_ARRAY(r->entries, t->entries, t->entry_count);
684 release_tree_content(t);
685 return r;
688 static struct tree_entry *new_tree_entry(void)
690 struct tree_entry *e;
692 if (!avail_tree_entry) {
693 unsigned int n = tree_entry_alloc;
694 tree_entry_allocd += n * sizeof(struct tree_entry);
695 ALLOC_ARRAY(e, n);
696 avail_tree_entry = e;
697 while (n-- > 1) {
698 *((void**)e) = e + 1;
699 e++;
701 *((void**)e) = NULL;
704 e = avail_tree_entry;
705 avail_tree_entry = *((void**)e);
706 return e;
709 static void release_tree_entry(struct tree_entry *e)
711 if (e->tree)
712 release_tree_content_recursive(e->tree);
713 *((void**)e) = avail_tree_entry;
714 avail_tree_entry = e;
717 static struct tree_content *dup_tree_content(struct tree_content *s)
719 struct tree_content *d;
720 struct tree_entry *a, *b;
721 unsigned int i;
723 if (!s)
724 return NULL;
725 d = new_tree_content(s->entry_count);
726 for (i = 0; i < s->entry_count; i++) {
727 a = s->entries[i];
728 b = new_tree_entry();
729 memcpy(b, a, sizeof(*a));
730 if (a->tree && is_null_oid(&b->versions[1].oid))
731 b->tree = dup_tree_content(a->tree);
732 else
733 b->tree = NULL;
734 d->entries[i] = b;
736 d->entry_count = s->entry_count;
737 d->delta_depth = s->delta_depth;
739 return d;
742 static void start_packfile(void)
744 struct strbuf tmp_file = STRBUF_INIT;
745 struct packed_git *p;
746 int pack_fd;
748 pack_fd = odb_mkstemp(&tmp_file, "pack/tmp_pack_XXXXXX");
749 FLEX_ALLOC_STR(p, pack_name, tmp_file.buf);
750 strbuf_release(&tmp_file);
752 p->pack_fd = pack_fd;
753 p->do_not_close = 1;
754 pack_file = hashfd(pack_fd, p->pack_name);
756 pack_data = p;
757 pack_size = write_pack_header(pack_file, 0);
758 object_count = 0;
760 REALLOC_ARRAY(all_packs, pack_id + 1);
761 all_packs[pack_id] = p;
764 static const char *create_index(void)
766 const char *tmpfile;
767 struct pack_idx_entry **idx, **c, **last;
768 struct object_entry *e;
769 struct object_entry_pool *o;
771 /* Build the table of object IDs. */
772 ALLOC_ARRAY(idx, object_count);
773 c = idx;
774 for (o = blocks; o; o = o->next_pool)
775 for (e = o->next_free; e-- != o->entries;)
776 if (pack_id == e->pack_id)
777 *c++ = &e->idx;
778 last = idx + object_count;
779 if (c != last)
780 die("internal consistency error creating the index");
782 tmpfile = write_idx_file(NULL, idx, object_count, &pack_idx_opts,
783 pack_data->hash);
784 free(idx);
785 return tmpfile;
788 static char *keep_pack(const char *curr_index_name)
790 static const char *keep_msg = "fast-import";
791 struct strbuf name = STRBUF_INIT;
792 int keep_fd;
794 odb_pack_name(&name, pack_data->hash, "keep");
795 keep_fd = odb_pack_keep(name.buf);
796 if (keep_fd < 0)
797 die_errno("cannot create keep file");
798 write_or_die(keep_fd, keep_msg, strlen(keep_msg));
799 if (close(keep_fd))
800 die_errno("failed to write keep file");
802 odb_pack_name(&name, pack_data->hash, "pack");
803 if (finalize_object_file(pack_data->pack_name, name.buf))
804 die("cannot store pack file");
806 odb_pack_name(&name, pack_data->hash, "idx");
807 if (finalize_object_file(curr_index_name, name.buf))
808 die("cannot store index file");
809 free((void *)curr_index_name);
810 return strbuf_detach(&name, NULL);
813 static void unkeep_all_packs(void)
815 struct strbuf name = STRBUF_INIT;
816 int k;
818 for (k = 0; k < pack_id; k++) {
819 struct packed_git *p = all_packs[k];
820 odb_pack_name(&name, p->hash, "keep");
821 unlink_or_warn(name.buf);
823 strbuf_release(&name);
826 static int loosen_small_pack(const struct packed_git *p)
828 struct child_process unpack = CHILD_PROCESS_INIT;
830 if (lseek(p->pack_fd, 0, SEEK_SET) < 0)
831 die_errno("Failed seeking to start of '%s'", p->pack_name);
833 unpack.in = p->pack_fd;
834 unpack.git_cmd = 1;
835 unpack.stdout_to_stderr = 1;
836 strvec_push(&unpack.args, "unpack-objects");
837 if (!show_stats)
838 strvec_push(&unpack.args, "-q");
840 return run_command(&unpack);
843 static void end_packfile(void)
845 static int running;
847 if (running || !pack_data)
848 return;
850 running = 1;
851 clear_delta_base_cache();
852 if (object_count) {
853 struct packed_git *new_p;
854 struct object_id cur_pack_oid;
855 char *idx_name;
856 int i;
857 struct branch *b;
858 struct tag *t;
860 close_pack_windows(pack_data);
861 finalize_hashfile(pack_file, cur_pack_oid.hash, 0);
862 fixup_pack_header_footer(pack_data->pack_fd, pack_data->hash,
863 pack_data->pack_name, object_count,
864 cur_pack_oid.hash, pack_size);
866 if (object_count <= unpack_limit) {
867 if (!loosen_small_pack(pack_data)) {
868 invalidate_pack_id(pack_id);
869 goto discard_pack;
873 close(pack_data->pack_fd);
874 idx_name = keep_pack(create_index());
876 /* Register the packfile with core git's machinery. */
877 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
878 if (!new_p)
879 die("core git rejected index %s", idx_name);
880 all_packs[pack_id] = new_p;
881 install_packed_git(the_repository, new_p);
882 free(idx_name);
884 /* Print the boundary */
885 if (pack_edges) {
886 fprintf(pack_edges, "%s:", new_p->pack_name);
887 for (i = 0; i < branch_table_sz; i++) {
888 for (b = branch_table[i]; b; b = b->table_next_branch) {
889 if (b->pack_id == pack_id)
890 fprintf(pack_edges, " %s",
891 oid_to_hex(&b->oid));
894 for (t = first_tag; t; t = t->next_tag) {
895 if (t->pack_id == pack_id)
896 fprintf(pack_edges, " %s",
897 oid_to_hex(&t->oid));
899 fputc('\n', pack_edges);
900 fflush(pack_edges);
903 pack_id++;
905 else {
906 discard_pack:
907 close(pack_data->pack_fd);
908 unlink_or_warn(pack_data->pack_name);
910 FREE_AND_NULL(pack_data);
911 running = 0;
913 /* We can't carry a delta across packfiles. */
914 strbuf_release(&last_blob.data);
915 last_blob.offset = 0;
916 last_blob.depth = 0;
919 static void cycle_packfile(void)
921 end_packfile();
922 start_packfile();
925 static int store_object(
926 enum object_type type,
927 struct strbuf *dat,
928 struct last_object *last,
929 struct object_id *oidout,
930 uintmax_t mark)
932 void *out, *delta;
933 struct object_entry *e;
934 unsigned char hdr[96];
935 struct object_id oid;
936 unsigned long hdrlen, deltalen;
937 git_hash_ctx c;
938 git_zstream s;
940 hdrlen = xsnprintf((char *)hdr, sizeof(hdr), "%s %lu",
941 type_name(type), (unsigned long)dat->len) + 1;
942 the_hash_algo->init_fn(&c);
943 the_hash_algo->update_fn(&c, hdr, hdrlen);
944 the_hash_algo->update_fn(&c, dat->buf, dat->len);
945 the_hash_algo->final_oid_fn(&oid, &c);
946 if (oidout)
947 oidcpy(oidout, &oid);
949 e = insert_object(&oid);
950 if (mark)
951 insert_mark(&marks, mark, e);
952 if (e->idx.offset) {
953 duplicate_count_by_type[type]++;
954 return 1;
955 } else if (find_sha1_pack(oid.hash,
956 get_all_packs(the_repository))) {
957 e->type = type;
958 e->pack_id = MAX_PACK_ID;
959 e->idx.offset = 1; /* just not zero! */
960 duplicate_count_by_type[type]++;
961 return 1;
964 if (last && last->data.len && last->data.buf && last->depth < max_depth
965 && dat->len > the_hash_algo->rawsz) {
967 delta_count_attempts_by_type[type]++;
968 delta = diff_delta(last->data.buf, last->data.len,
969 dat->buf, dat->len,
970 &deltalen, dat->len - the_hash_algo->rawsz);
971 } else
972 delta = NULL;
974 git_deflate_init(&s, pack_compression_level);
975 if (delta) {
976 s.next_in = delta;
977 s.avail_in = deltalen;
978 } else {
979 s.next_in = (void *)dat->buf;
980 s.avail_in = dat->len;
982 s.avail_out = git_deflate_bound(&s, s.avail_in);
983 s.next_out = out = xmalloc(s.avail_out);
984 while (git_deflate(&s, Z_FINISH) == Z_OK)
985 ; /* nothing */
986 git_deflate_end(&s);
988 /* Determine if we should auto-checkpoint. */
989 if ((max_packsize
990 && (pack_size + PACK_SIZE_THRESHOLD + s.total_out) > max_packsize)
991 || (pack_size + PACK_SIZE_THRESHOLD + s.total_out) < pack_size) {
993 /* This new object needs to *not* have the current pack_id. */
994 e->pack_id = pack_id + 1;
995 cycle_packfile();
997 /* We cannot carry a delta into the new pack. */
998 if (delta) {
999 FREE_AND_NULL(delta);
1001 git_deflate_init(&s, pack_compression_level);
1002 s.next_in = (void *)dat->buf;
1003 s.avail_in = dat->len;
1004 s.avail_out = git_deflate_bound(&s, s.avail_in);
1005 s.next_out = out = xrealloc(out, s.avail_out);
1006 while (git_deflate(&s, Z_FINISH) == Z_OK)
1007 ; /* nothing */
1008 git_deflate_end(&s);
1012 e->type = type;
1013 e->pack_id = pack_id;
1014 e->idx.offset = pack_size;
1015 object_count++;
1016 object_count_by_type[type]++;
1018 crc32_begin(pack_file);
1020 if (delta) {
1021 off_t ofs = e->idx.offset - last->offset;
1022 unsigned pos = sizeof(hdr) - 1;
1024 delta_count_by_type[type]++;
1025 e->depth = last->depth + 1;
1027 hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1028 OBJ_OFS_DELTA, deltalen);
1029 hashwrite(pack_file, hdr, hdrlen);
1030 pack_size += hdrlen;
1032 hdr[pos] = ofs & 127;
1033 while (ofs >>= 7)
1034 hdr[--pos] = 128 | (--ofs & 127);
1035 hashwrite(pack_file, hdr + pos, sizeof(hdr) - pos);
1036 pack_size += sizeof(hdr) - pos;
1037 } else {
1038 e->depth = 0;
1039 hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1040 type, dat->len);
1041 hashwrite(pack_file, hdr, hdrlen);
1042 pack_size += hdrlen;
1045 hashwrite(pack_file, out, s.total_out);
1046 pack_size += s.total_out;
1048 e->idx.crc32 = crc32_end(pack_file);
1050 free(out);
1051 free(delta);
1052 if (last) {
1053 if (last->no_swap) {
1054 last->data = *dat;
1055 } else {
1056 strbuf_swap(&last->data, dat);
1058 last->offset = e->idx.offset;
1059 last->depth = e->depth;
1061 return 0;
1064 static void truncate_pack(struct hashfile_checkpoint *checkpoint)
1066 if (hashfile_truncate(pack_file, checkpoint))
1067 die_errno("cannot truncate pack to skip duplicate");
1068 pack_size = checkpoint->offset;
1071 static void stream_blob(uintmax_t len, struct object_id *oidout, uintmax_t mark)
1073 size_t in_sz = 64 * 1024, out_sz = 64 * 1024;
1074 unsigned char *in_buf = xmalloc(in_sz);
1075 unsigned char *out_buf = xmalloc(out_sz);
1076 struct object_entry *e;
1077 struct object_id oid;
1078 unsigned long hdrlen;
1079 off_t offset;
1080 git_hash_ctx c;
1081 git_zstream s;
1082 struct hashfile_checkpoint checkpoint;
1083 int status = Z_OK;
1085 /* Determine if we should auto-checkpoint. */
1086 if ((max_packsize
1087 && (pack_size + PACK_SIZE_THRESHOLD + len) > max_packsize)
1088 || (pack_size + PACK_SIZE_THRESHOLD + len) < pack_size)
1089 cycle_packfile();
1091 hashfile_checkpoint(pack_file, &checkpoint);
1092 offset = checkpoint.offset;
1094 hdrlen = xsnprintf((char *)out_buf, out_sz, "blob %" PRIuMAX, len) + 1;
1096 the_hash_algo->init_fn(&c);
1097 the_hash_algo->update_fn(&c, out_buf, hdrlen);
1099 crc32_begin(pack_file);
1101 git_deflate_init(&s, pack_compression_level);
1103 hdrlen = encode_in_pack_object_header(out_buf, out_sz, OBJ_BLOB, len);
1105 s.next_out = out_buf + hdrlen;
1106 s.avail_out = out_sz - hdrlen;
1108 while (status != Z_STREAM_END) {
1109 if (0 < len && !s.avail_in) {
1110 size_t cnt = in_sz < len ? in_sz : (size_t)len;
1111 size_t n = fread(in_buf, 1, cnt, stdin);
1112 if (!n && feof(stdin))
1113 die("EOF in data (%" PRIuMAX " bytes remaining)", len);
1115 the_hash_algo->update_fn(&c, in_buf, n);
1116 s.next_in = in_buf;
1117 s.avail_in = n;
1118 len -= n;
1121 status = git_deflate(&s, len ? 0 : Z_FINISH);
1123 if (!s.avail_out || status == Z_STREAM_END) {
1124 size_t n = s.next_out - out_buf;
1125 hashwrite(pack_file, out_buf, n);
1126 pack_size += n;
1127 s.next_out = out_buf;
1128 s.avail_out = out_sz;
1131 switch (status) {
1132 case Z_OK:
1133 case Z_BUF_ERROR:
1134 case Z_STREAM_END:
1135 continue;
1136 default:
1137 die("unexpected deflate failure: %d", status);
1140 git_deflate_end(&s);
1141 the_hash_algo->final_oid_fn(&oid, &c);
1143 if (oidout)
1144 oidcpy(oidout, &oid);
1146 e = insert_object(&oid);
1148 if (mark)
1149 insert_mark(&marks, mark, e);
1151 if (e->idx.offset) {
1152 duplicate_count_by_type[OBJ_BLOB]++;
1153 truncate_pack(&checkpoint);
1155 } else if (find_sha1_pack(oid.hash,
1156 get_all_packs(the_repository))) {
1157 e->type = OBJ_BLOB;
1158 e->pack_id = MAX_PACK_ID;
1159 e->idx.offset = 1; /* just not zero! */
1160 duplicate_count_by_type[OBJ_BLOB]++;
1161 truncate_pack(&checkpoint);
1163 } else {
1164 e->depth = 0;
1165 e->type = OBJ_BLOB;
1166 e->pack_id = pack_id;
1167 e->idx.offset = offset;
1168 e->idx.crc32 = crc32_end(pack_file);
1169 object_count++;
1170 object_count_by_type[OBJ_BLOB]++;
1173 free(in_buf);
1174 free(out_buf);
1177 /* All calls must be guarded by find_object() or find_mark() to
1178 * ensure the 'struct object_entry' passed was written by this
1179 * process instance. We unpack the entry by the offset, avoiding
1180 * the need for the corresponding .idx file. This unpacking rule
1181 * works because we only use OBJ_REF_DELTA within the packfiles
1182 * created by fast-import.
1184 * oe must not be NULL. Such an oe usually comes from giving
1185 * an unknown SHA-1 to find_object() or an undefined mark to
1186 * find_mark(). Callers must test for this condition and use
1187 * the standard read_sha1_file() when it happens.
1189 * oe->pack_id must not be MAX_PACK_ID. Such an oe is usually from
1190 * find_mark(), where the mark was reloaded from an existing marks
1191 * file and is referencing an object that this fast-import process
1192 * instance did not write out to a packfile. Callers must test for
1193 * this condition and use read_sha1_file() instead.
1195 static void *gfi_unpack_entry(
1196 struct object_entry *oe,
1197 unsigned long *sizep)
1199 enum object_type type;
1200 struct packed_git *p = all_packs[oe->pack_id];
1201 if (p == pack_data && p->pack_size < (pack_size + the_hash_algo->rawsz)) {
1202 /* The object is stored in the packfile we are writing to
1203 * and we have modified it since the last time we scanned
1204 * back to read a previously written object. If an old
1205 * window covered [p->pack_size, p->pack_size + rawsz) its
1206 * data is stale and is not valid. Closing all windows
1207 * and updating the packfile length ensures we can read
1208 * the newly written data.
1210 close_pack_windows(p);
1211 hashflush(pack_file);
1213 /* We have to offer rawsz bytes additional on the end of
1214 * the packfile as the core unpacker code assumes the
1215 * footer is present at the file end and must promise
1216 * at least rawsz bytes within any window it maps. But
1217 * we don't actually create the footer here.
1219 p->pack_size = pack_size + the_hash_algo->rawsz;
1221 return unpack_entry(the_repository, p, oe->idx.offset, &type, sizep);
1224 static const char *get_mode(const char *str, uint16_t *modep)
1226 unsigned char c;
1227 uint16_t mode = 0;
1229 while ((c = *str++) != ' ') {
1230 if (c < '0' || c > '7')
1231 return NULL;
1232 mode = (mode << 3) + (c - '0');
1234 *modep = mode;
1235 return str;
1238 static void load_tree(struct tree_entry *root)
1240 struct object_id *oid = &root->versions[1].oid;
1241 struct object_entry *myoe;
1242 struct tree_content *t;
1243 unsigned long size;
1244 char *buf;
1245 const char *c;
1247 root->tree = t = new_tree_content(8);
1248 if (is_null_oid(oid))
1249 return;
1251 myoe = find_object(oid);
1252 if (myoe && myoe->pack_id != MAX_PACK_ID) {
1253 if (myoe->type != OBJ_TREE)
1254 die("Not a tree: %s", oid_to_hex(oid));
1255 t->delta_depth = myoe->depth;
1256 buf = gfi_unpack_entry(myoe, &size);
1257 if (!buf)
1258 die("Can't load tree %s", oid_to_hex(oid));
1259 } else {
1260 enum object_type type;
1261 buf = read_object_file(oid, &type, &size);
1262 if (!buf || type != OBJ_TREE)
1263 die("Can't load tree %s", oid_to_hex(oid));
1266 c = buf;
1267 while (c != (buf + size)) {
1268 struct tree_entry *e = new_tree_entry();
1270 if (t->entry_count == t->entry_capacity)
1271 root->tree = t = grow_tree_content(t, t->entry_count);
1272 t->entries[t->entry_count++] = e;
1274 e->tree = NULL;
1275 c = get_mode(c, &e->versions[1].mode);
1276 if (!c)
1277 die("Corrupt mode in %s", oid_to_hex(oid));
1278 e->versions[0].mode = e->versions[1].mode;
1279 e->name = to_atom(c, strlen(c));
1280 c += e->name->str_len + 1;
1281 oidread(&e->versions[0].oid, (unsigned char *)c);
1282 oidread(&e->versions[1].oid, (unsigned char *)c);
1283 c += the_hash_algo->rawsz;
1285 free(buf);
1288 static int tecmp0 (const void *_a, const void *_b)
1290 struct tree_entry *a = *((struct tree_entry**)_a);
1291 struct tree_entry *b = *((struct tree_entry**)_b);
1292 return base_name_compare(
1293 a->name->str_dat, a->name->str_len, a->versions[0].mode,
1294 b->name->str_dat, b->name->str_len, b->versions[0].mode);
1297 static int tecmp1 (const void *_a, const void *_b)
1299 struct tree_entry *a = *((struct tree_entry**)_a);
1300 struct tree_entry *b = *((struct tree_entry**)_b);
1301 return base_name_compare(
1302 a->name->str_dat, a->name->str_len, a->versions[1].mode,
1303 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1306 static void mktree(struct tree_content *t, int v, struct strbuf *b)
1308 size_t maxlen = 0;
1309 unsigned int i;
1311 if (!v)
1312 QSORT(t->entries, t->entry_count, tecmp0);
1313 else
1314 QSORT(t->entries, t->entry_count, tecmp1);
1316 for (i = 0; i < t->entry_count; i++) {
1317 if (t->entries[i]->versions[v].mode)
1318 maxlen += t->entries[i]->name->str_len + 34;
1321 strbuf_reset(b);
1322 strbuf_grow(b, maxlen);
1323 for (i = 0; i < t->entry_count; i++) {
1324 struct tree_entry *e = t->entries[i];
1325 if (!e->versions[v].mode)
1326 continue;
1327 strbuf_addf(b, "%o %s%c",
1328 (unsigned int)(e->versions[v].mode & ~NO_DELTA),
1329 e->name->str_dat, '\0');
1330 strbuf_add(b, e->versions[v].oid.hash, the_hash_algo->rawsz);
1334 static void store_tree(struct tree_entry *root)
1336 struct tree_content *t;
1337 unsigned int i, j, del;
1338 struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1339 struct object_entry *le = NULL;
1341 if (!is_null_oid(&root->versions[1].oid))
1342 return;
1344 if (!root->tree)
1345 load_tree(root);
1346 t = root->tree;
1348 for (i = 0; i < t->entry_count; i++) {
1349 if (t->entries[i]->tree)
1350 store_tree(t->entries[i]);
1353 if (!(root->versions[0].mode & NO_DELTA))
1354 le = find_object(&root->versions[0].oid);
1355 if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1356 mktree(t, 0, &old_tree);
1357 lo.data = old_tree;
1358 lo.offset = le->idx.offset;
1359 lo.depth = t->delta_depth;
1362 mktree(t, 1, &new_tree);
1363 store_object(OBJ_TREE, &new_tree, &lo, &root->versions[1].oid, 0);
1365 t->delta_depth = lo.depth;
1366 for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1367 struct tree_entry *e = t->entries[i];
1368 if (e->versions[1].mode) {
1369 e->versions[0].mode = e->versions[1].mode;
1370 oidcpy(&e->versions[0].oid, &e->versions[1].oid);
1371 t->entries[j++] = e;
1372 } else {
1373 release_tree_entry(e);
1374 del++;
1377 t->entry_count -= del;
1380 static void tree_content_replace(
1381 struct tree_entry *root,
1382 const struct object_id *oid,
1383 const uint16_t mode,
1384 struct tree_content *newtree)
1386 if (!S_ISDIR(mode))
1387 die("Root cannot be a non-directory");
1388 oidclr(&root->versions[0].oid);
1389 oidcpy(&root->versions[1].oid, oid);
1390 if (root->tree)
1391 release_tree_content_recursive(root->tree);
1392 root->tree = newtree;
1395 static int tree_content_set(
1396 struct tree_entry *root,
1397 const char *p,
1398 const struct object_id *oid,
1399 const uint16_t mode,
1400 struct tree_content *subtree)
1402 struct tree_content *t;
1403 const char *slash1;
1404 unsigned int i, n;
1405 struct tree_entry *e;
1407 slash1 = strchrnul(p, '/');
1408 n = slash1 - p;
1409 if (!n)
1410 die("Empty path component found in input");
1411 if (!*slash1 && !S_ISDIR(mode) && subtree)
1412 die("Non-directories cannot have subtrees");
1414 if (!root->tree)
1415 load_tree(root);
1416 t = root->tree;
1417 for (i = 0; i < t->entry_count; i++) {
1418 e = t->entries[i];
1419 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1420 if (!*slash1) {
1421 if (!S_ISDIR(mode)
1422 && e->versions[1].mode == mode
1423 && oideq(&e->versions[1].oid, oid))
1424 return 0;
1425 e->versions[1].mode = mode;
1426 oidcpy(&e->versions[1].oid, oid);
1427 if (e->tree)
1428 release_tree_content_recursive(e->tree);
1429 e->tree = subtree;
1432 * We need to leave e->versions[0].sha1 alone
1433 * to avoid modifying the preimage tree used
1434 * when writing out the parent directory.
1435 * But after replacing the subdir with a
1436 * completely different one, it's not a good
1437 * delta base any more, and besides, we've
1438 * thrown away the tree entries needed to
1439 * make a delta against it.
1441 * So let's just explicitly disable deltas
1442 * for the subtree.
1444 if (S_ISDIR(e->versions[0].mode))
1445 e->versions[0].mode |= NO_DELTA;
1447 oidclr(&root->versions[1].oid);
1448 return 1;
1450 if (!S_ISDIR(e->versions[1].mode)) {
1451 e->tree = new_tree_content(8);
1452 e->versions[1].mode = S_IFDIR;
1454 if (!e->tree)
1455 load_tree(e);
1456 if (tree_content_set(e, slash1 + 1, oid, mode, subtree)) {
1457 oidclr(&root->versions[1].oid);
1458 return 1;
1460 return 0;
1464 if (t->entry_count == t->entry_capacity)
1465 root->tree = t = grow_tree_content(t, t->entry_count);
1466 e = new_tree_entry();
1467 e->name = to_atom(p, n);
1468 e->versions[0].mode = 0;
1469 oidclr(&e->versions[0].oid);
1470 t->entries[t->entry_count++] = e;
1471 if (*slash1) {
1472 e->tree = new_tree_content(8);
1473 e->versions[1].mode = S_IFDIR;
1474 tree_content_set(e, slash1 + 1, oid, mode, subtree);
1475 } else {
1476 e->tree = subtree;
1477 e->versions[1].mode = mode;
1478 oidcpy(&e->versions[1].oid, oid);
1480 oidclr(&root->versions[1].oid);
1481 return 1;
1484 static int tree_content_remove(
1485 struct tree_entry *root,
1486 const char *p,
1487 struct tree_entry *backup_leaf,
1488 int allow_root)
1490 struct tree_content *t;
1491 const char *slash1;
1492 unsigned int i, n;
1493 struct tree_entry *e;
1495 slash1 = strchrnul(p, '/');
1496 n = slash1 - p;
1498 if (!root->tree)
1499 load_tree(root);
1501 if (!*p && allow_root) {
1502 e = root;
1503 goto del_entry;
1506 t = root->tree;
1507 for (i = 0; i < t->entry_count; i++) {
1508 e = t->entries[i];
1509 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1510 if (*slash1 && !S_ISDIR(e->versions[1].mode))
1512 * If p names a file in some subdirectory, and a
1513 * file or symlink matching the name of the
1514 * parent directory of p exists, then p cannot
1515 * exist and need not be deleted.
1517 return 1;
1518 if (!*slash1 || !S_ISDIR(e->versions[1].mode))
1519 goto del_entry;
1520 if (!e->tree)
1521 load_tree(e);
1522 if (tree_content_remove(e, slash1 + 1, backup_leaf, 0)) {
1523 for (n = 0; n < e->tree->entry_count; n++) {
1524 if (e->tree->entries[n]->versions[1].mode) {
1525 oidclr(&root->versions[1].oid);
1526 return 1;
1529 backup_leaf = NULL;
1530 goto del_entry;
1532 return 0;
1535 return 0;
1537 del_entry:
1538 if (backup_leaf)
1539 memcpy(backup_leaf, e, sizeof(*backup_leaf));
1540 else if (e->tree)
1541 release_tree_content_recursive(e->tree);
1542 e->tree = NULL;
1543 e->versions[1].mode = 0;
1544 oidclr(&e->versions[1].oid);
1545 oidclr(&root->versions[1].oid);
1546 return 1;
1549 static int tree_content_get(
1550 struct tree_entry *root,
1551 const char *p,
1552 struct tree_entry *leaf,
1553 int allow_root)
1555 struct tree_content *t;
1556 const char *slash1;
1557 unsigned int i, n;
1558 struct tree_entry *e;
1560 slash1 = strchrnul(p, '/');
1561 n = slash1 - p;
1562 if (!n && !allow_root)
1563 die("Empty path component found in input");
1565 if (!root->tree)
1566 load_tree(root);
1568 if (!n) {
1569 e = root;
1570 goto found_entry;
1573 t = root->tree;
1574 for (i = 0; i < t->entry_count; i++) {
1575 e = t->entries[i];
1576 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1577 if (!*slash1)
1578 goto found_entry;
1579 if (!S_ISDIR(e->versions[1].mode))
1580 return 0;
1581 if (!e->tree)
1582 load_tree(e);
1583 return tree_content_get(e, slash1 + 1, leaf, 0);
1586 return 0;
1588 found_entry:
1589 memcpy(leaf, e, sizeof(*leaf));
1590 if (e->tree && is_null_oid(&e->versions[1].oid))
1591 leaf->tree = dup_tree_content(e->tree);
1592 else
1593 leaf->tree = NULL;
1594 return 1;
1597 static int update_branch(struct branch *b)
1599 static const char *msg = "fast-import";
1600 struct ref_transaction *transaction;
1601 struct object_id old_oid;
1602 struct strbuf err = STRBUF_INIT;
1604 if (is_null_oid(&b->oid)) {
1605 if (b->delete)
1606 delete_ref(NULL, b->name, NULL, 0);
1607 return 0;
1609 if (read_ref(b->name, &old_oid))
1610 oidclr(&old_oid);
1611 if (!force_update && !is_null_oid(&old_oid)) {
1612 struct commit *old_cmit, *new_cmit;
1614 old_cmit = lookup_commit_reference_gently(the_repository,
1615 &old_oid, 0);
1616 new_cmit = lookup_commit_reference_gently(the_repository,
1617 &b->oid, 0);
1618 if (!old_cmit || !new_cmit)
1619 return error("Branch %s is missing commits.", b->name);
1621 if (!in_merge_bases(old_cmit, new_cmit)) {
1622 warning("Not updating %s"
1623 " (new tip %s does not contain %s)",
1624 b->name, oid_to_hex(&b->oid),
1625 oid_to_hex(&old_oid));
1626 return -1;
1629 transaction = ref_transaction_begin(&err);
1630 if (!transaction ||
1631 ref_transaction_update(transaction, b->name, &b->oid, &old_oid,
1632 0, msg, &err) ||
1633 ref_transaction_commit(transaction, &err)) {
1634 ref_transaction_free(transaction);
1635 error("%s", err.buf);
1636 strbuf_release(&err);
1637 return -1;
1639 ref_transaction_free(transaction);
1640 strbuf_release(&err);
1641 return 0;
1644 static void dump_branches(void)
1646 unsigned int i;
1647 struct branch *b;
1649 for (i = 0; i < branch_table_sz; i++) {
1650 for (b = branch_table[i]; b; b = b->table_next_branch)
1651 failure |= update_branch(b);
1655 static void dump_tags(void)
1657 static const char *msg = "fast-import";
1658 struct tag *t;
1659 struct strbuf ref_name = STRBUF_INIT;
1660 struct strbuf err = STRBUF_INIT;
1661 struct ref_transaction *transaction;
1663 transaction = ref_transaction_begin(&err);
1664 if (!transaction) {
1665 failure |= error("%s", err.buf);
1666 goto cleanup;
1668 for (t = first_tag; t; t = t->next_tag) {
1669 strbuf_reset(&ref_name);
1670 strbuf_addf(&ref_name, "refs/tags/%s", t->name);
1672 if (ref_transaction_update(transaction, ref_name.buf,
1673 &t->oid, NULL, 0, msg, &err)) {
1674 failure |= error("%s", err.buf);
1675 goto cleanup;
1678 if (ref_transaction_commit(transaction, &err))
1679 failure |= error("%s", err.buf);
1681 cleanup:
1682 ref_transaction_free(transaction);
1683 strbuf_release(&ref_name);
1684 strbuf_release(&err);
1687 static void dump_marks(void)
1689 struct lock_file mark_lock = LOCK_INIT;
1690 FILE *f;
1692 if (!export_marks_file || (import_marks_file && !import_marks_file_done))
1693 return;
1695 if (safe_create_leading_directories_const(export_marks_file)) {
1696 failure |= error_errno("unable to create leading directories of %s",
1697 export_marks_file);
1698 return;
1701 if (hold_lock_file_for_update(&mark_lock, export_marks_file, 0) < 0) {
1702 failure |= error_errno("Unable to write marks file %s",
1703 export_marks_file);
1704 return;
1707 f = fdopen_lock_file(&mark_lock, "w");
1708 if (!f) {
1709 int saved_errno = errno;
1710 rollback_lock_file(&mark_lock);
1711 failure |= error("Unable to write marks file %s: %s",
1712 export_marks_file, strerror(saved_errno));
1713 return;
1716 for_each_mark(marks, 0, dump_marks_fn, f);
1717 if (commit_lock_file(&mark_lock)) {
1718 failure |= error_errno("Unable to write file %s",
1719 export_marks_file);
1720 return;
1724 static void insert_object_entry(struct mark_set **s, struct object_id *oid, uintmax_t mark)
1726 struct object_entry *e;
1727 e = find_object(oid);
1728 if (!e) {
1729 enum object_type type = oid_object_info(the_repository,
1730 oid, NULL);
1731 if (type < 0)
1732 die("object not found: %s", oid_to_hex(oid));
1733 e = insert_object(oid);
1734 e->type = type;
1735 e->pack_id = MAX_PACK_ID;
1736 e->idx.offset = 1; /* just not zero! */
1738 insert_mark(s, mark, e);
1741 static void insert_oid_entry(struct mark_set **s, struct object_id *oid, uintmax_t mark)
1743 insert_mark(s, mark, xmemdupz(oid, sizeof(*oid)));
1746 static void read_mark_file(struct mark_set **s, FILE *f, mark_set_inserter_t inserter)
1748 char line[512];
1749 while (fgets(line, sizeof(line), f)) {
1750 uintmax_t mark;
1751 char *end;
1752 struct object_id oid;
1754 /* Ensure SHA-1 objects are padded with zeros. */
1755 memset(oid.hash, 0, sizeof(oid.hash));
1757 end = strchr(line, '\n');
1758 if (line[0] != ':' || !end)
1759 die("corrupt mark line: %s", line);
1760 *end = 0;
1761 mark = strtoumax(line + 1, &end, 10);
1762 if (!mark || end == line + 1
1763 || *end != ' '
1764 || get_oid_hex_any(end + 1, &oid) == GIT_HASH_UNKNOWN)
1765 die("corrupt mark line: %s", line);
1766 inserter(s, &oid, mark);
1770 static void read_marks(void)
1772 FILE *f = fopen(import_marks_file, "r");
1773 if (f)
1775 else if (import_marks_file_ignore_missing && errno == ENOENT)
1776 goto done; /* Marks file does not exist */
1777 else
1778 die_errno("cannot read '%s'", import_marks_file);
1779 read_mark_file(&marks, f, insert_object_entry);
1780 fclose(f);
1781 done:
1782 import_marks_file_done = 1;
1786 static int read_next_command(void)
1788 static int stdin_eof = 0;
1790 if (stdin_eof) {
1791 unread_command_buf = 0;
1792 return EOF;
1795 for (;;) {
1796 if (unread_command_buf) {
1797 unread_command_buf = 0;
1798 } else {
1799 struct recent_command *rc;
1801 stdin_eof = strbuf_getline_lf(&command_buf, stdin);
1802 if (stdin_eof)
1803 return EOF;
1805 if (!seen_data_command
1806 && !starts_with(command_buf.buf, "feature ")
1807 && !starts_with(command_buf.buf, "option ")) {
1808 parse_argv();
1811 rc = rc_free;
1812 if (rc)
1813 rc_free = rc->next;
1814 else {
1815 rc = cmd_hist.next;
1816 cmd_hist.next = rc->next;
1817 cmd_hist.next->prev = &cmd_hist;
1818 free(rc->buf);
1821 rc->buf = xstrdup(command_buf.buf);
1822 rc->prev = cmd_tail;
1823 rc->next = cmd_hist.prev;
1824 rc->prev->next = rc;
1825 cmd_tail = rc;
1827 if (command_buf.buf[0] == '#')
1828 continue;
1829 return 0;
1833 static void skip_optional_lf(void)
1835 int term_char = fgetc(stdin);
1836 if (term_char != '\n' && term_char != EOF)
1837 ungetc(term_char, stdin);
1840 static void parse_mark(void)
1842 const char *v;
1843 if (skip_prefix(command_buf.buf, "mark :", &v)) {
1844 next_mark = strtoumax(v, NULL, 10);
1845 read_next_command();
1847 else
1848 next_mark = 0;
1851 static void parse_original_identifier(void)
1853 const char *v;
1854 if (skip_prefix(command_buf.buf, "original-oid ", &v))
1855 read_next_command();
1858 static int parse_data(struct strbuf *sb, uintmax_t limit, uintmax_t *len_res)
1860 const char *data;
1861 strbuf_reset(sb);
1863 if (!skip_prefix(command_buf.buf, "data ", &data))
1864 die("Expected 'data n' command, found: %s", command_buf.buf);
1866 if (skip_prefix(data, "<<", &data)) {
1867 char *term = xstrdup(data);
1868 size_t term_len = command_buf.len - (data - command_buf.buf);
1870 for (;;) {
1871 if (strbuf_getline_lf(&command_buf, stdin) == EOF)
1872 die("EOF in data (terminator '%s' not found)", term);
1873 if (term_len == command_buf.len
1874 && !strcmp(term, command_buf.buf))
1875 break;
1876 strbuf_addbuf(sb, &command_buf);
1877 strbuf_addch(sb, '\n');
1879 free(term);
1881 else {
1882 uintmax_t len = strtoumax(data, NULL, 10);
1883 size_t n = 0, length = (size_t)len;
1885 if (limit && limit < len) {
1886 *len_res = len;
1887 return 0;
1889 if (length < len)
1890 die("data is too large to use in this context");
1892 while (n < length) {
1893 size_t s = strbuf_fread(sb, length - n, stdin);
1894 if (!s && feof(stdin))
1895 die("EOF in data (%lu bytes remaining)",
1896 (unsigned long)(length - n));
1897 n += s;
1901 skip_optional_lf();
1902 return 1;
1905 static int validate_raw_date(const char *src, struct strbuf *result, int strict)
1907 const char *orig_src = src;
1908 char *endp;
1909 unsigned long num;
1911 errno = 0;
1913 num = strtoul(src, &endp, 10);
1915 * NEEDSWORK: perhaps check for reasonable values? For example, we
1916 * could error on values representing times more than a
1917 * day in the future.
1919 if (errno || endp == src || *endp != ' ')
1920 return -1;
1922 src = endp + 1;
1923 if (*src != '-' && *src != '+')
1924 return -1;
1926 num = strtoul(src + 1, &endp, 10);
1928 * NEEDSWORK: check for brokenness other than num > 1400, such as
1929 * (num % 100) >= 60, or ((num % 100) % 15) != 0 ?
1931 if (errno || endp == src + 1 || *endp || /* did not parse */
1932 (strict && (1400 < num)) /* parsed a broken timezone */
1934 return -1;
1936 strbuf_addstr(result, orig_src);
1937 return 0;
1940 static char *parse_ident(const char *buf)
1942 const char *ltgt;
1943 size_t name_len;
1944 struct strbuf ident = STRBUF_INIT;
1946 /* ensure there is a space delimiter even if there is no name */
1947 if (*buf == '<')
1948 --buf;
1950 ltgt = buf + strcspn(buf, "<>");
1951 if (*ltgt != '<')
1952 die("Missing < in ident string: %s", buf);
1953 if (ltgt != buf && ltgt[-1] != ' ')
1954 die("Missing space before < in ident string: %s", buf);
1955 ltgt = ltgt + 1 + strcspn(ltgt + 1, "<>");
1956 if (*ltgt != '>')
1957 die("Missing > in ident string: %s", buf);
1958 ltgt++;
1959 if (*ltgt != ' ')
1960 die("Missing space after > in ident string: %s", buf);
1961 ltgt++;
1962 name_len = ltgt - buf;
1963 strbuf_add(&ident, buf, name_len);
1965 switch (whenspec) {
1966 case WHENSPEC_RAW:
1967 if (validate_raw_date(ltgt, &ident, 1) < 0)
1968 die("Invalid raw date \"%s\" in ident: %s", ltgt, buf);
1969 break;
1970 case WHENSPEC_RAW_PERMISSIVE:
1971 if (validate_raw_date(ltgt, &ident, 0) < 0)
1972 die("Invalid raw date \"%s\" in ident: %s", ltgt, buf);
1973 break;
1974 case WHENSPEC_RFC2822:
1975 if (parse_date(ltgt, &ident) < 0)
1976 die("Invalid rfc2822 date \"%s\" in ident: %s", ltgt, buf);
1977 break;
1978 case WHENSPEC_NOW:
1979 if (strcmp("now", ltgt))
1980 die("Date in ident must be 'now': %s", buf);
1981 datestamp(&ident);
1982 break;
1985 return strbuf_detach(&ident, NULL);
1988 static void parse_and_store_blob(
1989 struct last_object *last,
1990 struct object_id *oidout,
1991 uintmax_t mark)
1993 static struct strbuf buf = STRBUF_INIT;
1994 uintmax_t len;
1996 if (parse_data(&buf, big_file_threshold, &len))
1997 store_object(OBJ_BLOB, &buf, last, oidout, mark);
1998 else {
1999 if (last) {
2000 strbuf_release(&last->data);
2001 last->offset = 0;
2002 last->depth = 0;
2004 stream_blob(len, oidout, mark);
2005 skip_optional_lf();
2009 static void parse_new_blob(void)
2011 read_next_command();
2012 parse_mark();
2013 parse_original_identifier();
2014 parse_and_store_blob(&last_blob, NULL, next_mark);
2017 static void unload_one_branch(void)
2019 while (cur_active_branches
2020 && cur_active_branches >= max_active_branches) {
2021 uintmax_t min_commit = ULONG_MAX;
2022 struct branch *e, *l = NULL, *p = NULL;
2024 for (e = active_branches; e; e = e->active_next_branch) {
2025 if (e->last_commit < min_commit) {
2026 p = l;
2027 min_commit = e->last_commit;
2029 l = e;
2032 if (p) {
2033 e = p->active_next_branch;
2034 p->active_next_branch = e->active_next_branch;
2035 } else {
2036 e = active_branches;
2037 active_branches = e->active_next_branch;
2039 e->active = 0;
2040 e->active_next_branch = NULL;
2041 if (e->branch_tree.tree) {
2042 release_tree_content_recursive(e->branch_tree.tree);
2043 e->branch_tree.tree = NULL;
2045 cur_active_branches--;
2049 static void load_branch(struct branch *b)
2051 load_tree(&b->branch_tree);
2052 if (!b->active) {
2053 b->active = 1;
2054 b->active_next_branch = active_branches;
2055 active_branches = b;
2056 cur_active_branches++;
2057 branch_load_count++;
2061 static unsigned char convert_num_notes_to_fanout(uintmax_t num_notes)
2063 unsigned char fanout = 0;
2064 while ((num_notes >>= 8))
2065 fanout++;
2066 return fanout;
2069 static void construct_path_with_fanout(const char *hex_sha1,
2070 unsigned char fanout, char *path)
2072 unsigned int i = 0, j = 0;
2073 if (fanout >= the_hash_algo->rawsz)
2074 die("Too large fanout (%u)", fanout);
2075 while (fanout) {
2076 path[i++] = hex_sha1[j++];
2077 path[i++] = hex_sha1[j++];
2078 path[i++] = '/';
2079 fanout--;
2081 memcpy(path + i, hex_sha1 + j, the_hash_algo->hexsz - j);
2082 path[i + the_hash_algo->hexsz - j] = '\0';
2085 static uintmax_t do_change_note_fanout(
2086 struct tree_entry *orig_root, struct tree_entry *root,
2087 char *hex_oid, unsigned int hex_oid_len,
2088 char *fullpath, unsigned int fullpath_len,
2089 unsigned char fanout)
2091 struct tree_content *t;
2092 struct tree_entry *e, leaf;
2093 unsigned int i, tmp_hex_oid_len, tmp_fullpath_len;
2094 uintmax_t num_notes = 0;
2095 struct object_id oid;
2096 /* hex oid + '/' between each pair of hex digits + NUL */
2097 char realpath[GIT_MAX_HEXSZ + ((GIT_MAX_HEXSZ / 2) - 1) + 1];
2098 const unsigned hexsz = the_hash_algo->hexsz;
2100 if (!root->tree)
2101 load_tree(root);
2102 t = root->tree;
2104 for (i = 0; t && i < t->entry_count; i++) {
2105 e = t->entries[i];
2106 tmp_hex_oid_len = hex_oid_len + e->name->str_len;
2107 tmp_fullpath_len = fullpath_len;
2110 * We're interested in EITHER existing note entries (entries
2111 * with exactly 40 hex chars in path, not including directory
2112 * separators), OR directory entries that may contain note
2113 * entries (with < 40 hex chars in path).
2114 * Also, each path component in a note entry must be a multiple
2115 * of 2 chars.
2117 if (!e->versions[1].mode ||
2118 tmp_hex_oid_len > hexsz ||
2119 e->name->str_len % 2)
2120 continue;
2122 /* This _may_ be a note entry, or a subdir containing notes */
2123 memcpy(hex_oid + hex_oid_len, e->name->str_dat,
2124 e->name->str_len);
2125 if (tmp_fullpath_len)
2126 fullpath[tmp_fullpath_len++] = '/';
2127 memcpy(fullpath + tmp_fullpath_len, e->name->str_dat,
2128 e->name->str_len);
2129 tmp_fullpath_len += e->name->str_len;
2130 fullpath[tmp_fullpath_len] = '\0';
2132 if (tmp_hex_oid_len == hexsz && !get_oid_hex(hex_oid, &oid)) {
2133 /* This is a note entry */
2134 if (fanout == 0xff) {
2135 /* Counting mode, no rename */
2136 num_notes++;
2137 continue;
2139 construct_path_with_fanout(hex_oid, fanout, realpath);
2140 if (!strcmp(fullpath, realpath)) {
2141 /* Note entry is in correct location */
2142 num_notes++;
2143 continue;
2146 /* Rename fullpath to realpath */
2147 if (!tree_content_remove(orig_root, fullpath, &leaf, 0))
2148 die("Failed to remove path %s", fullpath);
2149 tree_content_set(orig_root, realpath,
2150 &leaf.versions[1].oid,
2151 leaf.versions[1].mode,
2152 leaf.tree);
2153 } else if (S_ISDIR(e->versions[1].mode)) {
2154 /* This is a subdir that may contain note entries */
2155 num_notes += do_change_note_fanout(orig_root, e,
2156 hex_oid, tmp_hex_oid_len,
2157 fullpath, tmp_fullpath_len, fanout);
2160 /* The above may have reallocated the current tree_content */
2161 t = root->tree;
2163 return num_notes;
2166 static uintmax_t change_note_fanout(struct tree_entry *root,
2167 unsigned char fanout)
2170 * The size of path is due to one slash between every two hex digits,
2171 * plus the terminating NUL. Note that there is no slash at the end, so
2172 * the number of slashes is one less than half the number of hex
2173 * characters.
2175 char hex_oid[GIT_MAX_HEXSZ], path[GIT_MAX_HEXSZ + (GIT_MAX_HEXSZ / 2) - 1 + 1];
2176 return do_change_note_fanout(root, root, hex_oid, 0, path, 0, fanout);
2179 static int parse_mapped_oid_hex(const char *hex, struct object_id *oid, const char **end)
2181 int algo;
2182 khiter_t it;
2184 /* Make SHA-1 object IDs have all-zero padding. */
2185 memset(oid->hash, 0, sizeof(oid->hash));
2187 algo = parse_oid_hex_any(hex, oid, end);
2188 if (algo == GIT_HASH_UNKNOWN)
2189 return -1;
2191 it = kh_get_oid_map(sub_oid_map, *oid);
2192 /* No such object? */
2193 if (it == kh_end(sub_oid_map)) {
2194 /* If we're using the same algorithm, pass it through. */
2195 if (hash_algos[algo].format_id == the_hash_algo->format_id)
2196 return 0;
2197 return -1;
2199 oidcpy(oid, kh_value(sub_oid_map, it));
2200 return 0;
2204 * Given a pointer into a string, parse a mark reference:
2206 * idnum ::= ':' bigint;
2208 * Return the first character after the value in *endptr.
2210 * Complain if the following character is not what is expected,
2211 * either a space or end of the string.
2213 static uintmax_t parse_mark_ref(const char *p, char **endptr)
2215 uintmax_t mark;
2217 assert(*p == ':');
2218 p++;
2219 mark = strtoumax(p, endptr, 10);
2220 if (*endptr == p)
2221 die("No value after ':' in mark: %s", command_buf.buf);
2222 return mark;
2226 * Parse the mark reference, and complain if this is not the end of
2227 * the string.
2229 static uintmax_t parse_mark_ref_eol(const char *p)
2231 char *end;
2232 uintmax_t mark;
2234 mark = parse_mark_ref(p, &end);
2235 if (*end != '\0')
2236 die("Garbage after mark: %s", command_buf.buf);
2237 return mark;
2241 * Parse the mark reference, demanding a trailing space. Return a
2242 * pointer to the space.
2244 static uintmax_t parse_mark_ref_space(const char **p)
2246 uintmax_t mark;
2247 char *end;
2249 mark = parse_mark_ref(*p, &end);
2250 if (*end++ != ' ')
2251 die("Missing space after mark: %s", command_buf.buf);
2252 *p = end;
2253 return mark;
2256 static void file_change_m(const char *p, struct branch *b)
2258 static struct strbuf uq = STRBUF_INIT;
2259 const char *endp;
2260 struct object_entry *oe;
2261 struct object_id oid;
2262 uint16_t mode, inline_data = 0;
2264 p = get_mode(p, &mode);
2265 if (!p)
2266 die("Corrupt mode: %s", command_buf.buf);
2267 switch (mode) {
2268 case 0644:
2269 case 0755:
2270 mode |= S_IFREG;
2271 case S_IFREG | 0644:
2272 case S_IFREG | 0755:
2273 case S_IFLNK:
2274 case S_IFDIR:
2275 case S_IFGITLINK:
2276 /* ok */
2277 break;
2278 default:
2279 die("Corrupt mode: %s", command_buf.buf);
2282 if (*p == ':') {
2283 oe = find_mark(marks, parse_mark_ref_space(&p));
2284 oidcpy(&oid, &oe->idx.oid);
2285 } else if (skip_prefix(p, "inline ", &p)) {
2286 inline_data = 1;
2287 oe = NULL; /* not used with inline_data, but makes gcc happy */
2288 } else {
2289 if (parse_mapped_oid_hex(p, &oid, &p))
2290 die("Invalid dataref: %s", command_buf.buf);
2291 oe = find_object(&oid);
2292 if (*p++ != ' ')
2293 die("Missing space after SHA1: %s", command_buf.buf);
2296 strbuf_reset(&uq);
2297 if (!unquote_c_style(&uq, p, &endp)) {
2298 if (*endp)
2299 die("Garbage after path in: %s", command_buf.buf);
2300 p = uq.buf;
2303 /* Git does not track empty, non-toplevel directories. */
2304 if (S_ISDIR(mode) && is_empty_tree_oid(&oid) && *p) {
2305 tree_content_remove(&b->branch_tree, p, NULL, 0);
2306 return;
2309 if (S_ISGITLINK(mode)) {
2310 if (inline_data)
2311 die("Git links cannot be specified 'inline': %s",
2312 command_buf.buf);
2313 else if (oe) {
2314 if (oe->type != OBJ_COMMIT)
2315 die("Not a commit (actually a %s): %s",
2316 type_name(oe->type), command_buf.buf);
2319 * Accept the sha1 without checking; it expected to be in
2320 * another repository.
2322 } else if (inline_data) {
2323 if (S_ISDIR(mode))
2324 die("Directories cannot be specified 'inline': %s",
2325 command_buf.buf);
2326 if (p != uq.buf) {
2327 strbuf_addstr(&uq, p);
2328 p = uq.buf;
2330 while (read_next_command() != EOF) {
2331 const char *v;
2332 if (skip_prefix(command_buf.buf, "cat-blob ", &v))
2333 parse_cat_blob(v);
2334 else {
2335 parse_and_store_blob(&last_blob, &oid, 0);
2336 break;
2339 } else {
2340 enum object_type expected = S_ISDIR(mode) ?
2341 OBJ_TREE: OBJ_BLOB;
2342 enum object_type type = oe ? oe->type :
2343 oid_object_info(the_repository, &oid,
2344 NULL);
2345 if (type < 0)
2346 die("%s not found: %s",
2347 S_ISDIR(mode) ? "Tree" : "Blob",
2348 command_buf.buf);
2349 if (type != expected)
2350 die("Not a %s (actually a %s): %s",
2351 type_name(expected), type_name(type),
2352 command_buf.buf);
2355 if (!*p) {
2356 tree_content_replace(&b->branch_tree, &oid, mode, NULL);
2357 return;
2359 tree_content_set(&b->branch_tree, p, &oid, mode, NULL);
2362 static void file_change_d(const char *p, struct branch *b)
2364 static struct strbuf uq = STRBUF_INIT;
2365 const char *endp;
2367 strbuf_reset(&uq);
2368 if (!unquote_c_style(&uq, p, &endp)) {
2369 if (*endp)
2370 die("Garbage after path in: %s", command_buf.buf);
2371 p = uq.buf;
2373 tree_content_remove(&b->branch_tree, p, NULL, 1);
2376 static void file_change_cr(const char *s, struct branch *b, int rename)
2378 const char *d;
2379 static struct strbuf s_uq = STRBUF_INIT;
2380 static struct strbuf d_uq = STRBUF_INIT;
2381 const char *endp;
2382 struct tree_entry leaf;
2384 strbuf_reset(&s_uq);
2385 if (!unquote_c_style(&s_uq, s, &endp)) {
2386 if (*endp != ' ')
2387 die("Missing space after source: %s", command_buf.buf);
2388 } else {
2389 endp = strchr(s, ' ');
2390 if (!endp)
2391 die("Missing space after source: %s", command_buf.buf);
2392 strbuf_add(&s_uq, s, endp - s);
2394 s = s_uq.buf;
2396 endp++;
2397 if (!*endp)
2398 die("Missing dest: %s", command_buf.buf);
2400 d = endp;
2401 strbuf_reset(&d_uq);
2402 if (!unquote_c_style(&d_uq, d, &endp)) {
2403 if (*endp)
2404 die("Garbage after dest in: %s", command_buf.buf);
2405 d = d_uq.buf;
2408 memset(&leaf, 0, sizeof(leaf));
2409 if (rename)
2410 tree_content_remove(&b->branch_tree, s, &leaf, 1);
2411 else
2412 tree_content_get(&b->branch_tree, s, &leaf, 1);
2413 if (!leaf.versions[1].mode)
2414 die("Path %s not in branch", s);
2415 if (!*d) { /* C "path/to/subdir" "" */
2416 tree_content_replace(&b->branch_tree,
2417 &leaf.versions[1].oid,
2418 leaf.versions[1].mode,
2419 leaf.tree);
2420 return;
2422 tree_content_set(&b->branch_tree, d,
2423 &leaf.versions[1].oid,
2424 leaf.versions[1].mode,
2425 leaf.tree);
2428 static void note_change_n(const char *p, struct branch *b, unsigned char *old_fanout)
2430 static struct strbuf uq = STRBUF_INIT;
2431 struct object_entry *oe;
2432 struct branch *s;
2433 struct object_id oid, commit_oid;
2434 char path[GIT_MAX_RAWSZ * 3];
2435 uint16_t inline_data = 0;
2436 unsigned char new_fanout;
2439 * When loading a branch, we don't traverse its tree to count the real
2440 * number of notes (too expensive to do this for all non-note refs).
2441 * This means that recently loaded notes refs might incorrectly have
2442 * b->num_notes == 0, and consequently, old_fanout might be wrong.
2444 * Fix this by traversing the tree and counting the number of notes
2445 * when b->num_notes == 0. If the notes tree is truly empty, the
2446 * calculation should not take long.
2448 if (b->num_notes == 0 && *old_fanout == 0) {
2449 /* Invoke change_note_fanout() in "counting mode". */
2450 b->num_notes = change_note_fanout(&b->branch_tree, 0xff);
2451 *old_fanout = convert_num_notes_to_fanout(b->num_notes);
2454 /* Now parse the notemodify command. */
2455 /* <dataref> or 'inline' */
2456 if (*p == ':') {
2457 oe = find_mark(marks, parse_mark_ref_space(&p));
2458 oidcpy(&oid, &oe->idx.oid);
2459 } else if (skip_prefix(p, "inline ", &p)) {
2460 inline_data = 1;
2461 oe = NULL; /* not used with inline_data, but makes gcc happy */
2462 } else {
2463 if (parse_mapped_oid_hex(p, &oid, &p))
2464 die("Invalid dataref: %s", command_buf.buf);
2465 oe = find_object(&oid);
2466 if (*p++ != ' ')
2467 die("Missing space after SHA1: %s", command_buf.buf);
2470 /* <commit-ish> */
2471 s = lookup_branch(p);
2472 if (s) {
2473 if (is_null_oid(&s->oid))
2474 die("Can't add a note on empty branch.");
2475 oidcpy(&commit_oid, &s->oid);
2476 } else if (*p == ':') {
2477 uintmax_t commit_mark = parse_mark_ref_eol(p);
2478 struct object_entry *commit_oe = find_mark(marks, commit_mark);
2479 if (commit_oe->type != OBJ_COMMIT)
2480 die("Mark :%" PRIuMAX " not a commit", commit_mark);
2481 oidcpy(&commit_oid, &commit_oe->idx.oid);
2482 } else if (!get_oid(p, &commit_oid)) {
2483 unsigned long size;
2484 char *buf = read_object_with_reference(the_repository,
2485 &commit_oid,
2486 commit_type, &size,
2487 &commit_oid);
2488 if (!buf || size < the_hash_algo->hexsz + 6)
2489 die("Not a valid commit: %s", p);
2490 free(buf);
2491 } else
2492 die("Invalid ref name or SHA1 expression: %s", p);
2494 if (inline_data) {
2495 if (p != uq.buf) {
2496 strbuf_addstr(&uq, p);
2497 p = uq.buf;
2499 read_next_command();
2500 parse_and_store_blob(&last_blob, &oid, 0);
2501 } else if (oe) {
2502 if (oe->type != OBJ_BLOB)
2503 die("Not a blob (actually a %s): %s",
2504 type_name(oe->type), command_buf.buf);
2505 } else if (!is_null_oid(&oid)) {
2506 enum object_type type = oid_object_info(the_repository, &oid,
2507 NULL);
2508 if (type < 0)
2509 die("Blob not found: %s", command_buf.buf);
2510 if (type != OBJ_BLOB)
2511 die("Not a blob (actually a %s): %s",
2512 type_name(type), command_buf.buf);
2515 construct_path_with_fanout(oid_to_hex(&commit_oid), *old_fanout, path);
2516 if (tree_content_remove(&b->branch_tree, path, NULL, 0))
2517 b->num_notes--;
2519 if (is_null_oid(&oid))
2520 return; /* nothing to insert */
2522 b->num_notes++;
2523 new_fanout = convert_num_notes_to_fanout(b->num_notes);
2524 construct_path_with_fanout(oid_to_hex(&commit_oid), new_fanout, path);
2525 tree_content_set(&b->branch_tree, path, &oid, S_IFREG | 0644, NULL);
2528 static void file_change_deleteall(struct branch *b)
2530 release_tree_content_recursive(b->branch_tree.tree);
2531 oidclr(&b->branch_tree.versions[0].oid);
2532 oidclr(&b->branch_tree.versions[1].oid);
2533 load_tree(&b->branch_tree);
2534 b->num_notes = 0;
2537 static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2539 if (!buf || size < the_hash_algo->hexsz + 6)
2540 die("Not a valid commit: %s", oid_to_hex(&b->oid));
2541 if (memcmp("tree ", buf, 5)
2542 || get_oid_hex(buf + 5, &b->branch_tree.versions[1].oid))
2543 die("The commit %s is corrupt", oid_to_hex(&b->oid));
2544 oidcpy(&b->branch_tree.versions[0].oid,
2545 &b->branch_tree.versions[1].oid);
2548 static void parse_from_existing(struct branch *b)
2550 if (is_null_oid(&b->oid)) {
2551 oidclr(&b->branch_tree.versions[0].oid);
2552 oidclr(&b->branch_tree.versions[1].oid);
2553 } else {
2554 unsigned long size;
2555 char *buf;
2557 buf = read_object_with_reference(the_repository,
2558 &b->oid, commit_type, &size,
2559 &b->oid);
2560 parse_from_commit(b, buf, size);
2561 free(buf);
2565 static int parse_objectish(struct branch *b, const char *objectish)
2567 struct branch *s;
2568 struct object_id oid;
2570 oidcpy(&oid, &b->branch_tree.versions[1].oid);
2572 s = lookup_branch(objectish);
2573 if (b == s)
2574 die("Can't create a branch from itself: %s", b->name);
2575 else if (s) {
2576 struct object_id *t = &s->branch_tree.versions[1].oid;
2577 oidcpy(&b->oid, &s->oid);
2578 oidcpy(&b->branch_tree.versions[0].oid, t);
2579 oidcpy(&b->branch_tree.versions[1].oid, t);
2580 } else if (*objectish == ':') {
2581 uintmax_t idnum = parse_mark_ref_eol(objectish);
2582 struct object_entry *oe = find_mark(marks, idnum);
2583 if (oe->type != OBJ_COMMIT)
2584 die("Mark :%" PRIuMAX " not a commit", idnum);
2585 if (!oideq(&b->oid, &oe->idx.oid)) {
2586 oidcpy(&b->oid, &oe->idx.oid);
2587 if (oe->pack_id != MAX_PACK_ID) {
2588 unsigned long size;
2589 char *buf = gfi_unpack_entry(oe, &size);
2590 parse_from_commit(b, buf, size);
2591 free(buf);
2592 } else
2593 parse_from_existing(b);
2595 } else if (!get_oid(objectish, &b->oid)) {
2596 parse_from_existing(b);
2597 if (is_null_oid(&b->oid))
2598 b->delete = 1;
2600 else
2601 die("Invalid ref name or SHA1 expression: %s", objectish);
2603 if (b->branch_tree.tree && !oideq(&oid, &b->branch_tree.versions[1].oid)) {
2604 release_tree_content_recursive(b->branch_tree.tree);
2605 b->branch_tree.tree = NULL;
2608 read_next_command();
2609 return 1;
2612 static int parse_from(struct branch *b)
2614 const char *from;
2616 if (!skip_prefix(command_buf.buf, "from ", &from))
2617 return 0;
2619 return parse_objectish(b, from);
2622 static int parse_objectish_with_prefix(struct branch *b, const char *prefix)
2624 const char *base;
2626 if (!skip_prefix(command_buf.buf, prefix, &base))
2627 return 0;
2629 return parse_objectish(b, base);
2632 static struct hash_list *parse_merge(unsigned int *count)
2634 struct hash_list *list = NULL, **tail = &list, *n;
2635 const char *from;
2636 struct branch *s;
2638 *count = 0;
2639 while (skip_prefix(command_buf.buf, "merge ", &from)) {
2640 n = xmalloc(sizeof(*n));
2641 s = lookup_branch(from);
2642 if (s)
2643 oidcpy(&n->oid, &s->oid);
2644 else if (*from == ':') {
2645 uintmax_t idnum = parse_mark_ref_eol(from);
2646 struct object_entry *oe = find_mark(marks, idnum);
2647 if (oe->type != OBJ_COMMIT)
2648 die("Mark :%" PRIuMAX " not a commit", idnum);
2649 oidcpy(&n->oid, &oe->idx.oid);
2650 } else if (!get_oid(from, &n->oid)) {
2651 unsigned long size;
2652 char *buf = read_object_with_reference(the_repository,
2653 &n->oid,
2654 commit_type,
2655 &size, &n->oid);
2656 if (!buf || size < the_hash_algo->hexsz + 6)
2657 die("Not a valid commit: %s", from);
2658 free(buf);
2659 } else
2660 die("Invalid ref name or SHA1 expression: %s", from);
2662 n->next = NULL;
2663 *tail = n;
2664 tail = &n->next;
2666 (*count)++;
2667 read_next_command();
2669 return list;
2672 static void parse_new_commit(const char *arg)
2674 static struct strbuf msg = STRBUF_INIT;
2675 struct branch *b;
2676 char *author = NULL;
2677 char *committer = NULL;
2678 char *encoding = NULL;
2679 struct hash_list *merge_list = NULL;
2680 unsigned int merge_count;
2681 unsigned char prev_fanout, new_fanout;
2682 const char *v;
2684 b = lookup_branch(arg);
2685 if (!b)
2686 b = new_branch(arg);
2688 read_next_command();
2689 parse_mark();
2690 parse_original_identifier();
2691 if (skip_prefix(command_buf.buf, "author ", &v)) {
2692 author = parse_ident(v);
2693 read_next_command();
2695 if (skip_prefix(command_buf.buf, "committer ", &v)) {
2696 committer = parse_ident(v);
2697 read_next_command();
2699 if (!committer)
2700 die("Expected committer but didn't get one");
2701 if (skip_prefix(command_buf.buf, "encoding ", &v)) {
2702 encoding = xstrdup(v);
2703 read_next_command();
2705 parse_data(&msg, 0, NULL);
2706 read_next_command();
2707 parse_from(b);
2708 merge_list = parse_merge(&merge_count);
2710 /* ensure the branch is active/loaded */
2711 if (!b->branch_tree.tree || !max_active_branches) {
2712 unload_one_branch();
2713 load_branch(b);
2716 prev_fanout = convert_num_notes_to_fanout(b->num_notes);
2718 /* file_change* */
2719 while (command_buf.len > 0) {
2720 if (skip_prefix(command_buf.buf, "M ", &v))
2721 file_change_m(v, b);
2722 else if (skip_prefix(command_buf.buf, "D ", &v))
2723 file_change_d(v, b);
2724 else if (skip_prefix(command_buf.buf, "R ", &v))
2725 file_change_cr(v, b, 1);
2726 else if (skip_prefix(command_buf.buf, "C ", &v))
2727 file_change_cr(v, b, 0);
2728 else if (skip_prefix(command_buf.buf, "N ", &v))
2729 note_change_n(v, b, &prev_fanout);
2730 else if (!strcmp("deleteall", command_buf.buf))
2731 file_change_deleteall(b);
2732 else if (skip_prefix(command_buf.buf, "ls ", &v))
2733 parse_ls(v, b);
2734 else if (skip_prefix(command_buf.buf, "cat-blob ", &v))
2735 parse_cat_blob(v);
2736 else {
2737 unread_command_buf = 1;
2738 break;
2740 if (read_next_command() == EOF)
2741 break;
2744 new_fanout = convert_num_notes_to_fanout(b->num_notes);
2745 if (new_fanout != prev_fanout)
2746 b->num_notes = change_note_fanout(&b->branch_tree, new_fanout);
2748 /* build the tree and the commit */
2749 store_tree(&b->branch_tree);
2750 oidcpy(&b->branch_tree.versions[0].oid,
2751 &b->branch_tree.versions[1].oid);
2753 strbuf_reset(&new_data);
2754 strbuf_addf(&new_data, "tree %s\n",
2755 oid_to_hex(&b->branch_tree.versions[1].oid));
2756 if (!is_null_oid(&b->oid))
2757 strbuf_addf(&new_data, "parent %s\n",
2758 oid_to_hex(&b->oid));
2759 while (merge_list) {
2760 struct hash_list *next = merge_list->next;
2761 strbuf_addf(&new_data, "parent %s\n",
2762 oid_to_hex(&merge_list->oid));
2763 free(merge_list);
2764 merge_list = next;
2766 strbuf_addf(&new_data,
2767 "author %s\n"
2768 "committer %s\n",
2769 author ? author : committer, committer);
2770 if (encoding)
2771 strbuf_addf(&new_data,
2772 "encoding %s\n",
2773 encoding);
2774 strbuf_addch(&new_data, '\n');
2775 strbuf_addbuf(&new_data, &msg);
2776 free(author);
2777 free(committer);
2778 free(encoding);
2780 if (!store_object(OBJ_COMMIT, &new_data, NULL, &b->oid, next_mark))
2781 b->pack_id = pack_id;
2782 b->last_commit = object_count_by_type[OBJ_COMMIT];
2785 static void parse_new_tag(const char *arg)
2787 static struct strbuf msg = STRBUF_INIT;
2788 const char *from;
2789 char *tagger;
2790 struct branch *s;
2791 struct tag *t;
2792 uintmax_t from_mark = 0;
2793 struct object_id oid;
2794 enum object_type type;
2795 const char *v;
2797 t = mem_pool_alloc(&fi_mem_pool, sizeof(struct tag));
2798 memset(t, 0, sizeof(struct tag));
2799 t->name = mem_pool_strdup(&fi_mem_pool, arg);
2800 if (last_tag)
2801 last_tag->next_tag = t;
2802 else
2803 first_tag = t;
2804 last_tag = t;
2805 read_next_command();
2806 parse_mark();
2808 /* from ... */
2809 if (!skip_prefix(command_buf.buf, "from ", &from))
2810 die("Expected from command, got %s", command_buf.buf);
2811 s = lookup_branch(from);
2812 if (s) {
2813 if (is_null_oid(&s->oid))
2814 die("Can't tag an empty branch.");
2815 oidcpy(&oid, &s->oid);
2816 type = OBJ_COMMIT;
2817 } else if (*from == ':') {
2818 struct object_entry *oe;
2819 from_mark = parse_mark_ref_eol(from);
2820 oe = find_mark(marks, from_mark);
2821 type = oe->type;
2822 oidcpy(&oid, &oe->idx.oid);
2823 } else if (!get_oid(from, &oid)) {
2824 struct object_entry *oe = find_object(&oid);
2825 if (!oe) {
2826 type = oid_object_info(the_repository, &oid, NULL);
2827 if (type < 0)
2828 die("Not a valid object: %s", from);
2829 } else
2830 type = oe->type;
2831 } else
2832 die("Invalid ref name or SHA1 expression: %s", from);
2833 read_next_command();
2835 /* original-oid ... */
2836 parse_original_identifier();
2838 /* tagger ... */
2839 if (skip_prefix(command_buf.buf, "tagger ", &v)) {
2840 tagger = parse_ident(v);
2841 read_next_command();
2842 } else
2843 tagger = NULL;
2845 /* tag payload/message */
2846 parse_data(&msg, 0, NULL);
2848 /* build the tag object */
2849 strbuf_reset(&new_data);
2851 strbuf_addf(&new_data,
2852 "object %s\n"
2853 "type %s\n"
2854 "tag %s\n",
2855 oid_to_hex(&oid), type_name(type), t->name);
2856 if (tagger)
2857 strbuf_addf(&new_data,
2858 "tagger %s\n", tagger);
2859 strbuf_addch(&new_data, '\n');
2860 strbuf_addbuf(&new_data, &msg);
2861 free(tagger);
2863 if (store_object(OBJ_TAG, &new_data, NULL, &t->oid, next_mark))
2864 t->pack_id = MAX_PACK_ID;
2865 else
2866 t->pack_id = pack_id;
2869 static void parse_reset_branch(const char *arg)
2871 struct branch *b;
2872 const char *tag_name;
2874 b = lookup_branch(arg);
2875 if (b) {
2876 oidclr(&b->oid);
2877 oidclr(&b->branch_tree.versions[0].oid);
2878 oidclr(&b->branch_tree.versions[1].oid);
2879 if (b->branch_tree.tree) {
2880 release_tree_content_recursive(b->branch_tree.tree);
2881 b->branch_tree.tree = NULL;
2884 else
2885 b = new_branch(arg);
2886 read_next_command();
2887 parse_from(b);
2888 if (b->delete && skip_prefix(b->name, "refs/tags/", &tag_name)) {
2890 * Elsewhere, we call dump_branches() before dump_tags(),
2891 * and dump_branches() will handle ref deletions first, so
2892 * in order to make sure the deletion actually takes effect,
2893 * we need to remove the tag from our list of tags to update.
2895 * NEEDSWORK: replace list of tags with hashmap for faster
2896 * deletion?
2898 struct tag *t, *prev = NULL;
2899 for (t = first_tag; t; t = t->next_tag) {
2900 if (!strcmp(t->name, tag_name))
2901 break;
2902 prev = t;
2904 if (t) {
2905 if (prev)
2906 prev->next_tag = t->next_tag;
2907 else
2908 first_tag = t->next_tag;
2909 if (!t->next_tag)
2910 last_tag = prev;
2911 /* There is no mem_pool_free(t) function to call. */
2914 if (command_buf.len > 0)
2915 unread_command_buf = 1;
2918 static void cat_blob_write(const char *buf, unsigned long size)
2920 if (write_in_full(cat_blob_fd, buf, size) < 0)
2921 die_errno("Write to frontend failed");
2924 static void cat_blob(struct object_entry *oe, struct object_id *oid)
2926 struct strbuf line = STRBUF_INIT;
2927 unsigned long size;
2928 enum object_type type = 0;
2929 char *buf;
2931 if (!oe || oe->pack_id == MAX_PACK_ID) {
2932 buf = read_object_file(oid, &type, &size);
2933 } else {
2934 type = oe->type;
2935 buf = gfi_unpack_entry(oe, &size);
2939 * Output based on batch_one_object() from cat-file.c.
2941 if (type <= 0) {
2942 strbuf_reset(&line);
2943 strbuf_addf(&line, "%s missing\n", oid_to_hex(oid));
2944 cat_blob_write(line.buf, line.len);
2945 strbuf_release(&line);
2946 free(buf);
2947 return;
2949 if (!buf)
2950 die("Can't read object %s", oid_to_hex(oid));
2951 if (type != OBJ_BLOB)
2952 die("Object %s is a %s but a blob was expected.",
2953 oid_to_hex(oid), type_name(type));
2954 strbuf_reset(&line);
2955 strbuf_addf(&line, "%s %s %"PRIuMAX"\n", oid_to_hex(oid),
2956 type_name(type), (uintmax_t)size);
2957 cat_blob_write(line.buf, line.len);
2958 strbuf_release(&line);
2959 cat_blob_write(buf, size);
2960 cat_blob_write("\n", 1);
2961 if (oe && oe->pack_id == pack_id) {
2962 last_blob.offset = oe->idx.offset;
2963 strbuf_attach(&last_blob.data, buf, size, size);
2964 last_blob.depth = oe->depth;
2965 } else
2966 free(buf);
2969 static void parse_get_mark(const char *p)
2971 struct object_entry *oe;
2972 char output[GIT_MAX_HEXSZ + 2];
2974 /* get-mark SP <object> LF */
2975 if (*p != ':')
2976 die("Not a mark: %s", p);
2978 oe = find_mark(marks, parse_mark_ref_eol(p));
2979 if (!oe)
2980 die("Unknown mark: %s", command_buf.buf);
2982 xsnprintf(output, sizeof(output), "%s\n", oid_to_hex(&oe->idx.oid));
2983 cat_blob_write(output, the_hash_algo->hexsz + 1);
2986 static void parse_cat_blob(const char *p)
2988 struct object_entry *oe;
2989 struct object_id oid;
2991 /* cat-blob SP <object> LF */
2992 if (*p == ':') {
2993 oe = find_mark(marks, parse_mark_ref_eol(p));
2994 if (!oe)
2995 die("Unknown mark: %s", command_buf.buf);
2996 oidcpy(&oid, &oe->idx.oid);
2997 } else {
2998 if (parse_mapped_oid_hex(p, &oid, &p))
2999 die("Invalid dataref: %s", command_buf.buf);
3000 if (*p)
3001 die("Garbage after SHA1: %s", command_buf.buf);
3002 oe = find_object(&oid);
3005 cat_blob(oe, &oid);
3008 static struct object_entry *dereference(struct object_entry *oe,
3009 struct object_id *oid)
3011 unsigned long size;
3012 char *buf = NULL;
3013 const unsigned hexsz = the_hash_algo->hexsz;
3015 if (!oe) {
3016 enum object_type type = oid_object_info(the_repository, oid,
3017 NULL);
3018 if (type < 0)
3019 die("object not found: %s", oid_to_hex(oid));
3020 /* cache it! */
3021 oe = insert_object(oid);
3022 oe->type = type;
3023 oe->pack_id = MAX_PACK_ID;
3024 oe->idx.offset = 1;
3026 switch (oe->type) {
3027 case OBJ_TREE: /* easy case. */
3028 return oe;
3029 case OBJ_COMMIT:
3030 case OBJ_TAG:
3031 break;
3032 default:
3033 die("Not a tree-ish: %s", command_buf.buf);
3036 if (oe->pack_id != MAX_PACK_ID) { /* in a pack being written */
3037 buf = gfi_unpack_entry(oe, &size);
3038 } else {
3039 enum object_type unused;
3040 buf = read_object_file(oid, &unused, &size);
3042 if (!buf)
3043 die("Can't load object %s", oid_to_hex(oid));
3045 /* Peel one layer. */
3046 switch (oe->type) {
3047 case OBJ_TAG:
3048 if (size < hexsz + strlen("object ") ||
3049 get_oid_hex(buf + strlen("object "), oid))
3050 die("Invalid SHA1 in tag: %s", command_buf.buf);
3051 break;
3052 case OBJ_COMMIT:
3053 if (size < hexsz + strlen("tree ") ||
3054 get_oid_hex(buf + strlen("tree "), oid))
3055 die("Invalid SHA1 in commit: %s", command_buf.buf);
3058 free(buf);
3059 return find_object(oid);
3062 static void insert_mapped_mark(uintmax_t mark, void *object, void *cbp)
3064 struct object_id *fromoid = object;
3065 struct object_id *tooid = find_mark(cbp, mark);
3066 int ret;
3067 khiter_t it;
3069 it = kh_put_oid_map(sub_oid_map, *fromoid, &ret);
3070 /* We've already seen this object. */
3071 if (ret == 0)
3072 return;
3073 kh_value(sub_oid_map, it) = tooid;
3076 static void build_mark_map_one(struct mark_set *from, struct mark_set *to)
3078 for_each_mark(from, 0, insert_mapped_mark, to);
3081 static void build_mark_map(struct string_list *from, struct string_list *to)
3083 struct string_list_item *fromp, *top;
3085 sub_oid_map = kh_init_oid_map();
3087 for_each_string_list_item(fromp, from) {
3088 top = string_list_lookup(to, fromp->string);
3089 if (!fromp->util) {
3090 die(_("Missing from marks for submodule '%s'"), fromp->string);
3091 } else if (!top || !top->util) {
3092 die(_("Missing to marks for submodule '%s'"), fromp->string);
3094 build_mark_map_one(fromp->util, top->util);
3098 static struct object_entry *parse_treeish_dataref(const char **p)
3100 struct object_id oid;
3101 struct object_entry *e;
3103 if (**p == ':') { /* <mark> */
3104 e = find_mark(marks, parse_mark_ref_space(p));
3105 if (!e)
3106 die("Unknown mark: %s", command_buf.buf);
3107 oidcpy(&oid, &e->idx.oid);
3108 } else { /* <sha1> */
3109 if (parse_mapped_oid_hex(*p, &oid, p))
3110 die("Invalid dataref: %s", command_buf.buf);
3111 e = find_object(&oid);
3112 if (*(*p)++ != ' ')
3113 die("Missing space after tree-ish: %s", command_buf.buf);
3116 while (!e || e->type != OBJ_TREE)
3117 e = dereference(e, &oid);
3118 return e;
3121 static void print_ls(int mode, const unsigned char *hash, const char *path)
3123 static struct strbuf line = STRBUF_INIT;
3125 /* See show_tree(). */
3126 const char *type =
3127 S_ISGITLINK(mode) ? commit_type :
3128 S_ISDIR(mode) ? tree_type :
3129 blob_type;
3131 if (!mode) {
3132 /* missing SP path LF */
3133 strbuf_reset(&line);
3134 strbuf_addstr(&line, "missing ");
3135 quote_c_style(path, &line, NULL, 0);
3136 strbuf_addch(&line, '\n');
3137 } else {
3138 /* mode SP type SP object_name TAB path LF */
3139 strbuf_reset(&line);
3140 strbuf_addf(&line, "%06o %s %s\t",
3141 mode & ~NO_DELTA, type, hash_to_hex(hash));
3142 quote_c_style(path, &line, NULL, 0);
3143 strbuf_addch(&line, '\n');
3145 cat_blob_write(line.buf, line.len);
3148 static void parse_ls(const char *p, struct branch *b)
3150 struct tree_entry *root = NULL;
3151 struct tree_entry leaf = {NULL};
3153 /* ls SP (<tree-ish> SP)? <path> */
3154 if (*p == '"') {
3155 if (!b)
3156 die("Not in a commit: %s", command_buf.buf);
3157 root = &b->branch_tree;
3158 } else {
3159 struct object_entry *e = parse_treeish_dataref(&p);
3160 root = new_tree_entry();
3161 oidcpy(&root->versions[1].oid, &e->idx.oid);
3162 if (!is_null_oid(&root->versions[1].oid))
3163 root->versions[1].mode = S_IFDIR;
3164 load_tree(root);
3166 if (*p == '"') {
3167 static struct strbuf uq = STRBUF_INIT;
3168 const char *endp;
3169 strbuf_reset(&uq);
3170 if (unquote_c_style(&uq, p, &endp))
3171 die("Invalid path: %s", command_buf.buf);
3172 if (*endp)
3173 die("Garbage after path in: %s", command_buf.buf);
3174 p = uq.buf;
3176 tree_content_get(root, p, &leaf, 1);
3178 * A directory in preparation would have a sha1 of zero
3179 * until it is saved. Save, for simplicity.
3181 if (S_ISDIR(leaf.versions[1].mode))
3182 store_tree(&leaf);
3184 print_ls(leaf.versions[1].mode, leaf.versions[1].oid.hash, p);
3185 if (leaf.tree)
3186 release_tree_content_recursive(leaf.tree);
3187 if (!b || root != &b->branch_tree)
3188 release_tree_entry(root);
3191 static void checkpoint(void)
3193 checkpoint_requested = 0;
3194 if (object_count) {
3195 cycle_packfile();
3197 dump_branches();
3198 dump_tags();
3199 dump_marks();
3202 static void parse_checkpoint(void)
3204 checkpoint_requested = 1;
3205 skip_optional_lf();
3208 static void parse_progress(void)
3210 fwrite(command_buf.buf, 1, command_buf.len, stdout);
3211 fputc('\n', stdout);
3212 fflush(stdout);
3213 skip_optional_lf();
3216 static void parse_alias(void)
3218 struct object_entry *e;
3219 struct branch b;
3221 skip_optional_lf();
3222 read_next_command();
3224 /* mark ... */
3225 parse_mark();
3226 if (!next_mark)
3227 die(_("Expected 'mark' command, got %s"), command_buf.buf);
3229 /* to ... */
3230 memset(&b, 0, sizeof(b));
3231 if (!parse_objectish_with_prefix(&b, "to "))
3232 die(_("Expected 'to' command, got %s"), command_buf.buf);
3233 e = find_object(&b.oid);
3234 assert(e);
3235 insert_mark(&marks, next_mark, e);
3238 static char* make_fast_import_path(const char *path)
3240 if (!relative_marks_paths || is_absolute_path(path))
3241 return xstrdup(path);
3242 return git_pathdup("info/fast-import/%s", path);
3245 static void option_import_marks(const char *marks,
3246 int from_stream, int ignore_missing)
3248 if (import_marks_file) {
3249 if (from_stream)
3250 die("Only one import-marks command allowed per stream");
3252 /* read previous mark file */
3253 if(!import_marks_file_from_stream)
3254 read_marks();
3257 import_marks_file = make_fast_import_path(marks);
3258 import_marks_file_from_stream = from_stream;
3259 import_marks_file_ignore_missing = ignore_missing;
3262 static void option_date_format(const char *fmt)
3264 if (!strcmp(fmt, "raw"))
3265 whenspec = WHENSPEC_RAW;
3266 else if (!strcmp(fmt, "raw-permissive"))
3267 whenspec = WHENSPEC_RAW_PERMISSIVE;
3268 else if (!strcmp(fmt, "rfc2822"))
3269 whenspec = WHENSPEC_RFC2822;
3270 else if (!strcmp(fmt, "now"))
3271 whenspec = WHENSPEC_NOW;
3272 else
3273 die("unknown --date-format argument %s", fmt);
3276 static unsigned long ulong_arg(const char *option, const char *arg)
3278 char *endptr;
3279 unsigned long rv = strtoul(arg, &endptr, 0);
3280 if (strchr(arg, '-') || endptr == arg || *endptr)
3281 die("%s: argument must be a non-negative integer", option);
3282 return rv;
3285 static void option_depth(const char *depth)
3287 max_depth = ulong_arg("--depth", depth);
3288 if (max_depth > MAX_DEPTH)
3289 die("--depth cannot exceed %u", MAX_DEPTH);
3292 static void option_active_branches(const char *branches)
3294 max_active_branches = ulong_arg("--active-branches", branches);
3297 static void option_export_marks(const char *marks)
3299 export_marks_file = make_fast_import_path(marks);
3302 static void option_cat_blob_fd(const char *fd)
3304 unsigned long n = ulong_arg("--cat-blob-fd", fd);
3305 if (n > (unsigned long) INT_MAX)
3306 die("--cat-blob-fd cannot exceed %d", INT_MAX);
3307 cat_blob_fd = (int) n;
3310 static void option_export_pack_edges(const char *edges)
3312 if (pack_edges)
3313 fclose(pack_edges);
3314 pack_edges = xfopen(edges, "a");
3317 static void option_rewrite_submodules(const char *arg, struct string_list *list)
3319 struct mark_set *ms;
3320 FILE *fp;
3321 char *s = xstrdup(arg);
3322 char *f = strchr(s, ':');
3323 if (!f)
3324 die(_("Expected format name:filename for submodule rewrite option"));
3325 *f = '\0';
3326 f++;
3327 CALLOC_ARRAY(ms, 1);
3329 fp = fopen(f, "r");
3330 if (!fp)
3331 die_errno("cannot read '%s'", f);
3332 read_mark_file(&ms, fp, insert_oid_entry);
3333 fclose(fp);
3335 string_list_insert(list, s)->util = ms;
3338 static int parse_one_option(const char *option)
3340 if (skip_prefix(option, "max-pack-size=", &option)) {
3341 unsigned long v;
3342 if (!git_parse_ulong(option, &v))
3343 return 0;
3344 if (v < 8192) {
3345 warning("max-pack-size is now in bytes, assuming --max-pack-size=%lum", v);
3346 v *= 1024 * 1024;
3347 } else if (v < 1024 * 1024) {
3348 warning("minimum max-pack-size is 1 MiB");
3349 v = 1024 * 1024;
3351 max_packsize = v;
3352 } else if (skip_prefix(option, "big-file-threshold=", &option)) {
3353 unsigned long v;
3354 if (!git_parse_ulong(option, &v))
3355 return 0;
3356 big_file_threshold = v;
3357 } else if (skip_prefix(option, "depth=", &option)) {
3358 option_depth(option);
3359 } else if (skip_prefix(option, "active-branches=", &option)) {
3360 option_active_branches(option);
3361 } else if (skip_prefix(option, "export-pack-edges=", &option)) {
3362 option_export_pack_edges(option);
3363 } else if (!strcmp(option, "quiet")) {
3364 show_stats = 0;
3365 } else if (!strcmp(option, "stats")) {
3366 show_stats = 1;
3367 } else if (!strcmp(option, "allow-unsafe-features")) {
3368 ; /* already handled during early option parsing */
3369 } else {
3370 return 0;
3373 return 1;
3376 static void check_unsafe_feature(const char *feature, int from_stream)
3378 if (from_stream && !allow_unsafe_features)
3379 die(_("feature '%s' forbidden in input without --allow-unsafe-features"),
3380 feature);
3383 static int parse_one_feature(const char *feature, int from_stream)
3385 const char *arg;
3387 if (skip_prefix(feature, "date-format=", &arg)) {
3388 option_date_format(arg);
3389 } else if (skip_prefix(feature, "import-marks=", &arg)) {
3390 check_unsafe_feature("import-marks", from_stream);
3391 option_import_marks(arg, from_stream, 0);
3392 } else if (skip_prefix(feature, "import-marks-if-exists=", &arg)) {
3393 check_unsafe_feature("import-marks-if-exists", from_stream);
3394 option_import_marks(arg, from_stream, 1);
3395 } else if (skip_prefix(feature, "export-marks=", &arg)) {
3396 check_unsafe_feature(feature, from_stream);
3397 option_export_marks(arg);
3398 } else if (!strcmp(feature, "alias")) {
3399 ; /* Don't die - this feature is supported */
3400 } else if (skip_prefix(feature, "rewrite-submodules-to=", &arg)) {
3401 option_rewrite_submodules(arg, &sub_marks_to);
3402 } else if (skip_prefix(feature, "rewrite-submodules-from=", &arg)) {
3403 option_rewrite_submodules(arg, &sub_marks_from);
3404 } else if (!strcmp(feature, "get-mark")) {
3405 ; /* Don't die - this feature is supported */
3406 } else if (!strcmp(feature, "cat-blob")) {
3407 ; /* Don't die - this feature is supported */
3408 } else if (!strcmp(feature, "relative-marks")) {
3409 relative_marks_paths = 1;
3410 } else if (!strcmp(feature, "no-relative-marks")) {
3411 relative_marks_paths = 0;
3412 } else if (!strcmp(feature, "done")) {
3413 require_explicit_termination = 1;
3414 } else if (!strcmp(feature, "force")) {
3415 force_update = 1;
3416 } else if (!strcmp(feature, "notes") || !strcmp(feature, "ls")) {
3417 ; /* do nothing; we have the feature */
3418 } else {
3419 return 0;
3422 return 1;
3425 static void parse_feature(const char *feature)
3427 if (seen_data_command)
3428 die("Got feature command '%s' after data command", feature);
3430 if (parse_one_feature(feature, 1))
3431 return;
3433 die("This version of fast-import does not support feature %s.", feature);
3436 static void parse_option(const char *option)
3438 if (seen_data_command)
3439 die("Got option command '%s' after data command", option);
3441 if (parse_one_option(option))
3442 return;
3444 die("This version of fast-import does not support option: %s", option);
3447 static void git_pack_config(void)
3449 int indexversion_value;
3450 int limit;
3451 unsigned long packsizelimit_value;
3453 if (!git_config_get_ulong("pack.depth", &max_depth)) {
3454 if (max_depth > MAX_DEPTH)
3455 max_depth = MAX_DEPTH;
3457 if (!git_config_get_int("pack.indexversion", &indexversion_value)) {
3458 pack_idx_opts.version = indexversion_value;
3459 if (pack_idx_opts.version > 2)
3460 git_die_config("pack.indexversion",
3461 "bad pack.indexversion=%"PRIu32, pack_idx_opts.version);
3463 if (!git_config_get_ulong("pack.packsizelimit", &packsizelimit_value))
3464 max_packsize = packsizelimit_value;
3466 if (!git_config_get_int("fastimport.unpacklimit", &limit))
3467 unpack_limit = limit;
3468 else if (!git_config_get_int("transfer.unpacklimit", &limit))
3469 unpack_limit = limit;
3471 git_config(git_default_config, NULL);
3474 static const char fast_import_usage[] =
3475 "git fast-import [--date-format=<f>] [--max-pack-size=<n>] [--big-file-threshold=<n>] [--depth=<n>] [--active-branches=<n>] [--export-marks=<marks.file>]";
3477 static void parse_argv(void)
3479 unsigned int i;
3481 for (i = 1; i < global_argc; i++) {
3482 const char *a = global_argv[i];
3484 if (*a != '-' || !strcmp(a, "--"))
3485 break;
3487 if (!skip_prefix(a, "--", &a))
3488 die("unknown option %s", a);
3490 if (parse_one_option(a))
3491 continue;
3493 if (parse_one_feature(a, 0))
3494 continue;
3496 if (skip_prefix(a, "cat-blob-fd=", &a)) {
3497 option_cat_blob_fd(a);
3498 continue;
3501 die("unknown option --%s", a);
3503 if (i != global_argc)
3504 usage(fast_import_usage);
3506 seen_data_command = 1;
3507 if (import_marks_file)
3508 read_marks();
3509 build_mark_map(&sub_marks_from, &sub_marks_to);
3512 int cmd_fast_import(int argc, const char **argv, const char *prefix)
3514 unsigned int i;
3516 if (argc == 2 && !strcmp(argv[1], "-h"))
3517 usage(fast_import_usage);
3519 reset_pack_idx_option(&pack_idx_opts);
3520 git_pack_config();
3522 alloc_objects(object_entry_alloc);
3523 strbuf_init(&command_buf, 0);
3524 CALLOC_ARRAY(atom_table, atom_table_sz);
3525 CALLOC_ARRAY(branch_table, branch_table_sz);
3526 CALLOC_ARRAY(avail_tree_table, avail_tree_table_sz);
3527 marks = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
3529 hashmap_init(&object_table, object_entry_hashcmp, NULL, 0);
3532 * We don't parse most options until after we've seen the set of
3533 * "feature" lines at the start of the stream (which allows the command
3534 * line to override stream data). But we must do an early parse of any
3535 * command-line options that impact how we interpret the feature lines.
3537 for (i = 1; i < argc; i++) {
3538 const char *arg = argv[i];
3539 if (*arg != '-' || !strcmp(arg, "--"))
3540 break;
3541 if (!strcmp(arg, "--allow-unsafe-features"))
3542 allow_unsafe_features = 1;
3545 global_argc = argc;
3546 global_argv = argv;
3548 rc_free = mem_pool_alloc(&fi_mem_pool, cmd_save * sizeof(*rc_free));
3549 for (i = 0; i < (cmd_save - 1); i++)
3550 rc_free[i].next = &rc_free[i + 1];
3551 rc_free[cmd_save - 1].next = NULL;
3553 start_packfile();
3554 set_die_routine(die_nicely);
3555 set_checkpoint_signal();
3556 while (read_next_command() != EOF) {
3557 const char *v;
3558 if (!strcmp("blob", command_buf.buf))
3559 parse_new_blob();
3560 else if (skip_prefix(command_buf.buf, "commit ", &v))
3561 parse_new_commit(v);
3562 else if (skip_prefix(command_buf.buf, "tag ", &v))
3563 parse_new_tag(v);
3564 else if (skip_prefix(command_buf.buf, "reset ", &v))
3565 parse_reset_branch(v);
3566 else if (skip_prefix(command_buf.buf, "ls ", &v))
3567 parse_ls(v, NULL);
3568 else if (skip_prefix(command_buf.buf, "cat-blob ", &v))
3569 parse_cat_blob(v);
3570 else if (skip_prefix(command_buf.buf, "get-mark ", &v))
3571 parse_get_mark(v);
3572 else if (!strcmp("checkpoint", command_buf.buf))
3573 parse_checkpoint();
3574 else if (!strcmp("done", command_buf.buf))
3575 break;
3576 else if (!strcmp("alias", command_buf.buf))
3577 parse_alias();
3578 else if (starts_with(command_buf.buf, "progress "))
3579 parse_progress();
3580 else if (skip_prefix(command_buf.buf, "feature ", &v))
3581 parse_feature(v);
3582 else if (skip_prefix(command_buf.buf, "option git ", &v))
3583 parse_option(v);
3584 else if (starts_with(command_buf.buf, "option "))
3585 /* ignore non-git options*/;
3586 else
3587 die("Unsupported command: %s", command_buf.buf);
3589 if (checkpoint_requested)
3590 checkpoint();
3593 /* argv hasn't been parsed yet, do so */
3594 if (!seen_data_command)
3595 parse_argv();
3597 if (require_explicit_termination && feof(stdin))
3598 die("stream ends early");
3600 end_packfile();
3602 dump_branches();
3603 dump_tags();
3604 unkeep_all_packs();
3605 dump_marks();
3607 if (pack_edges)
3608 fclose(pack_edges);
3610 if (show_stats) {
3611 uintmax_t total_count = 0, duplicate_count = 0;
3612 for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
3613 total_count += object_count_by_type[i];
3614 for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
3615 duplicate_count += duplicate_count_by_type[i];
3617 fprintf(stderr, "%s statistics:\n", argv[0]);
3618 fprintf(stderr, "---------------------------------------------------------------------\n");
3619 fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
3620 fprintf(stderr, "Total objects: %10" PRIuMAX " (%10" PRIuMAX " duplicates )\n", total_count, duplicate_count);
3621 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]);
3622 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]);
3623 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]);
3624 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]);
3625 fprintf(stderr, "Total branches: %10lu (%10lu loads )\n", branch_count, branch_load_count);
3626 fprintf(stderr, " marks: %10" PRIuMAX " (%10" PRIuMAX " unique )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
3627 fprintf(stderr, " atoms: %10u\n", atom_cnt);
3628 fprintf(stderr, "Memory total: %10" PRIuMAX " KiB\n", (tree_entry_allocd + fi_mem_pool.pool_alloc + alloc_count*sizeof(struct object_entry))/1024);
3629 fprintf(stderr, " pools: %10lu KiB\n", (unsigned long)((tree_entry_allocd + fi_mem_pool.pool_alloc) /1024));
3630 fprintf(stderr, " objects: %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
3631 fprintf(stderr, "---------------------------------------------------------------------\n");
3632 pack_report();
3633 fprintf(stderr, "---------------------------------------------------------------------\n");
3634 fprintf(stderr, "\n");
3637 return failure ? 1 : 0;