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