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