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