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