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