at commit a0189536

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