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