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