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