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