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