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