pack-objects: learn about pack index version 2
[git/git.git] / index-pack.c
CommitLineData
9cf6d335
SV
1#include "cache.h"
2#include "delta.h"
3#include "pack.h"
4#include "csum-file.h"
8e440259
PE
5#include "blob.h"
6#include "commit.h"
7#include "tag.h"
8#include "tree.h"
9cf6d335
SV
9
10static const char index_pack_usage[] =
b8077709 11"git-index-pack [-v] [-o <index-file>] [{ ---keep | --keep=<msg> }] { <pack-file> | --stdin [--fix-thin] [<pack-file>] }";
9cf6d335
SV
12
13struct object_entry
14{
d7dd0223 15 off_t offset;
2d477051
NP
16 unsigned long size;
17 unsigned int hdr_size;
ee5743ce 18 uint32_t crc32;
9cf6d335
SV
19 enum object_type type;
20 enum object_type real_type;
21 unsigned char sha1[20];
22};
23
53dda6ff
NP
24union delta_base {
25 unsigned char sha1[20];
d7dd0223 26 off_t offset;
53dda6ff
NP
27};
28
3c552873
NP
29/*
30 * Even if sizeof(union delta_base) == 24 on 64-bit archs, we really want
31 * to memcmp() only the first 20 bytes.
32 */
33#define UNION_BASE_SZ 20
34
9cf6d335
SV
35struct delta_entry
36{
53dda6ff 37 union delta_base base;
636171cb 38 int obj_no;
9cf6d335
SV
39};
40
9cf6d335
SV
41static struct object_entry *objects;
42static struct delta_entry *deltas;
43static int nr_objects;
44static int nr_deltas;
636171cb 45static int nr_resolved_deltas;
9cf6d335 46
e42797f5 47static int from_stdin;
3c9af366
NP
48static int verbose;
49
50static volatile sig_atomic_t progress_update;
51
52static void progress_interval(int signum)
53{
54 progress_update = 1;
55}
56
57static void setup_progress_signal(void)
58{
59 struct sigaction sa;
60 struct itimerval v;
61
62 memset(&sa, 0, sizeof(sa));
63 sa.sa_handler = progress_interval;
64 sigemptyset(&sa.sa_mask);
65 sa.sa_flags = SA_RESTART;
66 sigaction(SIGALRM, &sa, NULL);
67
68 v.it_interval.tv_sec = 1;
69 v.it_interval.tv_usec = 0;
70 v.it_value = v.it_interval;
71 setitimer(ITIMER_REAL, &v, NULL);
72
73}
74
75static unsigned display_progress(unsigned n, unsigned total, unsigned last_pc)
76{
77 unsigned percent = n * 100 / total;
78 if (percent != last_pc || progress_update) {
79 fprintf(stderr, "%4u%% (%u/%u) done\r", percent, n, total);
80 progress_update = 0;
81 }
82 return percent;
83}
e42797f5 84
2d477051
NP
85/* We always read in 4kB chunks. */
86static unsigned char input_buffer[4096];
d7dd0223
NP
87static unsigned int input_offset, input_len;
88static off_t consumed_bytes;
2d477051 89static SHA_CTX input_ctx;
ee5743ce 90static uint32_t input_crc32;
6d2fa7f1 91static int input_fd, output_fd, pack_fd;
2d477051 92
636171cb 93/* Discard current buffer used content. */
a6e8a767 94static void flush(void)
636171cb
NP
95{
96 if (input_offset) {
97 if (output_fd >= 0)
98 write_or_die(output_fd, input_buffer, input_offset);
99 SHA1_Update(&input_ctx, input_buffer, input_offset);
554a2636 100 memmove(input_buffer, input_buffer + input_offset, input_len);
636171cb
NP
101 input_offset = 0;
102 }
103}
104
2d477051
NP
105/*
106 * Make sure at least "min" bytes are available in the buffer, and
107 * return the pointer to the buffer.
108 */
b89c4e93 109static void *fill(int min)
9cf6d335 110{
2d477051
NP
111 if (min <= input_len)
112 return input_buffer + input_offset;
113 if (min > sizeof(input_buffer))
114 die("cannot fill %d bytes", min);
636171cb 115 flush();
2d477051
NP
116 do {
117 int ret = xread(input_fd, input_buffer + input_len,
118 sizeof(input_buffer) - input_len);
119 if (ret <= 0) {
120 if (!ret)
121 die("early EOF");
122 die("read error on input: %s", strerror(errno));
123 }
124 input_len += ret;
125 } while (input_len < min);
126 return input_buffer;
127}
128
129static void use(int bytes)
130{
131 if (bytes > input_len)
132 die("used more bytes than were available");
ee5743ce 133 input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
2d477051
NP
134 input_len -= bytes;
135 input_offset += bytes;
d7dd0223
NP
136
137 /* make sure off_t is sufficiently large not to wrap */
138 if (consumed_bytes > consumed_bytes + bytes)
139 die("pack too large for current definition of off_t");
2d477051
NP
140 consumed_bytes += bytes;
141}
9cf6d335 142
b89c4e93 143static const char *open_pack_file(const char *pack_name)
2d477051 144{
e42797f5
NP
145 if (from_stdin) {
146 input_fd = 0;
147 if (!pack_name) {
148 static char tmpfile[PATH_MAX];
149 snprintf(tmpfile, sizeof(tmpfile),
0e55181f 150 "%s/tmp_pack_XXXXXX", get_object_directory());
e42797f5
NP
151 output_fd = mkstemp(tmpfile);
152 pack_name = xstrdup(tmpfile);
153 } else
154 output_fd = open(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
155 if (output_fd < 0)
156 die("unable to create %s: %s\n", pack_name, strerror(errno));
6d2fa7f1 157 pack_fd = output_fd;
e42797f5
NP
158 } else {
159 input_fd = open(pack_name, O_RDONLY);
160 if (input_fd < 0)
161 die("cannot open packfile '%s': %s",
162 pack_name, strerror(errno));
163 output_fd = -1;
6d2fa7f1 164 pack_fd = input_fd;
e42797f5 165 }
2d477051 166 SHA1_Init(&input_ctx);
e42797f5 167 return pack_name;
9cf6d335
SV
168}
169
170static void parse_pack_header(void)
171{
2d477051 172 struct pack_header *hdr = fill(sizeof(struct pack_header));
9cf6d335
SV
173
174 /* Header consistency check */
9cf6d335 175 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
e42797f5 176 die("pack signature mismatch");
d60fc1c8 177 if (!pack_version_ok(hdr->hdr_version))
e42797f5 178 die("pack version %d unsupported", ntohl(hdr->hdr_version));
9cf6d335
SV
179
180 nr_objects = ntohl(hdr->hdr_entries);
2d477051 181 use(sizeof(struct pack_header));
9cf6d335
SV
182}
183
184static void bad_object(unsigned long offset, const char *format,
185 ...) NORETURN __attribute__((format (printf, 2, 3)));
186
187static void bad_object(unsigned long offset, const char *format, ...)
188{
189 va_list params;
190 char buf[1024];
191
192 va_start(params, format);
193 vsnprintf(buf, sizeof(buf), format, params);
194 va_end(params);
e42797f5 195 die("pack has bad object at offset %lu: %s", offset, buf);
9cf6d335
SV
196}
197
2d477051 198static void *unpack_entry_data(unsigned long offset, unsigned long size)
9cf6d335 199{
9cf6d335
SV
200 z_stream stream;
201 void *buf = xmalloc(size);
202
203 memset(&stream, 0, sizeof(stream));
204 stream.next_out = buf;
205 stream.avail_out = size;
2d477051
NP
206 stream.next_in = fill(1);
207 stream.avail_in = input_len;
9cf6d335
SV
208 inflateInit(&stream);
209
210 for (;;) {
211 int ret = inflate(&stream, 0);
2d477051
NP
212 use(input_len - stream.avail_in);
213 if (stream.total_out == size && ret == Z_STREAM_END)
9cf6d335
SV
214 break;
215 if (ret != Z_OK)
216 bad_object(offset, "inflate returned %d", ret);
2d477051
NP
217 stream.next_in = fill(1);
218 stream.avail_in = input_len;
9cf6d335
SV
219 }
220 inflateEnd(&stream);
9cf6d335
SV
221 return buf;
222}
223
2d477051 224static void *unpack_raw_entry(struct object_entry *obj, union delta_base *delta_base)
9cf6d335 225{
2d477051 226 unsigned char *p, c;
d7dd0223
NP
227 unsigned long size;
228 off_t base_offset;
9cf6d335 229 unsigned shift;
ee5743ce 230 void *data;
9cf6d335 231
2d477051 232 obj->offset = consumed_bytes;
ee5743ce 233 input_crc32 = crc32(0, Z_NULL, 0);
2d477051
NP
234
235 p = fill(1);
236 c = *p;
237 use(1);
238 obj->type = (c >> 4) & 7;
9cf6d335
SV
239 size = (c & 15);
240 shift = 4;
241 while (c & 0x80) {
2d477051
NP
242 p = fill(1);
243 c = *p;
244 use(1);
9cf6d335
SV
245 size += (c & 0x7fUL) << shift;
246 shift += 7;
247 }
2d477051 248 obj->size = size;
9cf6d335 249
2d477051 250 switch (obj->type) {
eb32d236 251 case OBJ_REF_DELTA:
2d477051
NP
252 hashcpy(delta_base->sha1, fill(20));
253 use(20);
53dda6ff
NP
254 break;
255 case OBJ_OFS_DELTA:
256 memset(delta_base, 0, sizeof(*delta_base));
2d477051
NP
257 p = fill(1);
258 c = *p;
259 use(1);
53dda6ff
NP
260 base_offset = c & 127;
261 while (c & 128) {
262 base_offset += 1;
8723f216 263 if (!base_offset || MSB(base_offset, 7))
2d477051
NP
264 bad_object(obj->offset, "offset value overflow for delta base object");
265 p = fill(1);
266 c = *p;
267 use(1);
53dda6ff
NP
268 base_offset = (base_offset << 7) + (c & 127);
269 }
2d477051
NP
270 delta_base->offset = obj->offset - base_offset;
271 if (delta_base->offset >= obj->offset)
272 bad_object(obj->offset, "delta base offset is out of bound");
53dda6ff 273 break;
9cf6d335
SV
274 case OBJ_COMMIT:
275 case OBJ_TREE:
276 case OBJ_BLOB:
277 case OBJ_TAG:
9cf6d335
SV
278 break;
279 default:
08a19d87 280 bad_object(obj->offset, "unknown object type %d", obj->type);
9cf6d335 281 }
2d477051
NP
282 obj->hdr_size = consumed_bytes - obj->offset;
283
ee5743ce
NP
284 data = unpack_entry_data(obj->offset, obj->size);
285 obj->crc32 = input_crc32;
286 return data;
2d477051
NP
287}
288
b89c4e93 289static void *get_data_from_pack(struct object_entry *obj)
2d477051
NP
290{
291 unsigned long from = obj[0].offset + obj[0].hdr_size;
292 unsigned long len = obj[1].offset - from;
a91d49cd 293 unsigned long rdy = 0;
6d2fa7f1 294 unsigned char *src, *data;
2d477051
NP
295 z_stream stream;
296 int st;
9cf6d335 297
6d2fa7f1 298 src = xmalloc(len);
a91d49cd
SP
299 data = src;
300 do {
301 ssize_t n = pread(pack_fd, data + rdy, len - rdy, from + rdy);
302 if (n <= 0)
303 die("cannot pread pack file: %s", strerror(errno));
304 rdy += n;
305 } while (rdy < len);
2d477051
NP
306 data = xmalloc(obj->size);
307 memset(&stream, 0, sizeof(stream));
308 stream.next_out = data;
309 stream.avail_out = obj->size;
6d2fa7f1 310 stream.next_in = src;
2d477051
NP
311 stream.avail_in = len;
312 inflateInit(&stream);
313 while ((st = inflate(&stream, Z_FINISH)) == Z_OK);
314 inflateEnd(&stream);
315 if (st != Z_STREAM_END || stream.total_out != obj->size)
316 die("serious inflate inconsistency");
6d2fa7f1 317 free(src);
9cf6d335
SV
318 return data;
319}
320
53dda6ff 321static int find_delta(const union delta_base *base)
9cf6d335
SV
322{
323 int first = 0, last = nr_deltas;
324
325 while (first < last) {
326 int next = (first + last) / 2;
327 struct delta_entry *delta = &deltas[next];
328 int cmp;
329
3c552873 330 cmp = memcmp(base, &delta->base, UNION_BASE_SZ);
9cf6d335
SV
331 if (!cmp)
332 return next;
333 if (cmp < 0) {
334 last = next;
335 continue;
336 }
337 first = next+1;
338 }
339 return -first-1;
340}
341
b89c4e93
NP
342static int find_delta_children(const union delta_base *base,
343 int *first_index, int *last_index)
9cf6d335 344{
53dda6ff 345 int first = find_delta(base);
9cf6d335
SV
346 int last = first;
347 int end = nr_deltas - 1;
348
349 if (first < 0)
350 return -1;
3c552873 351 while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
9cf6d335 352 --first;
3c552873 353 while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
9cf6d335
SV
354 ++last;
355 *first_index = first;
356 *last_index = last;
357 return 0;
358}
359
360static void sha1_object(const void *data, unsigned long size,
9096c660 361 enum object_type type, unsigned char *sha1)
9cf6d335 362{
ce9fbf16 363 hash_sha1_file(data, size, typename(type), sha1);
9096c660 364 if (has_sha1_file(sha1)) {
8685da42
NP
365 void *has_data;
366 enum object_type has_type;
367 unsigned long has_size;
368 has_data = read_sha1_file(sha1, &has_type, &has_size);
369 if (!has_data)
370 die("cannot read existing object %s", sha1_to_hex(sha1));
371 if (size != has_size || type != has_type ||
372 memcmp(data, has_data, size) != 0)
373 die("SHA1 COLLISION FOUND WITH %s !", sha1_to_hex(sha1));
bbf4b41b 374 free(has_data);
8685da42 375 }
9cf6d335
SV
376}
377
636171cb 378static void resolve_delta(struct object_entry *delta_obj, void *base_data,
9cf6d335
SV
379 unsigned long base_size, enum object_type type)
380{
9cf6d335
SV
381 void *delta_data;
382 unsigned long delta_size;
383 void *result;
384 unsigned long result_size;
53dda6ff 385 union delta_base delta_base;
9cf6d335
SV
386 int j, first, last;
387
636171cb
NP
388 delta_obj->real_type = type;
389 delta_data = get_data_from_pack(delta_obj);
390 delta_size = delta_obj->size;
9cf6d335
SV
391 result = patch_delta(base_data, base_size, delta_data, delta_size,
392 &result_size);
393 free(delta_data);
394 if (!result)
636171cb 395 bad_object(delta_obj->offset, "failed to apply delta");
9096c660 396 sha1_object(result, result_size, type, delta_obj->sha1);
636171cb 397 nr_resolved_deltas++;
53dda6ff 398
636171cb 399 hashcpy(delta_base.sha1, delta_obj->sha1);
b89c4e93 400 if (!find_delta_children(&delta_base, &first, &last)) {
636171cb
NP
401 for (j = first; j <= last; j++) {
402 struct object_entry *child = objects + deltas[j].obj_no;
403 if (child->real_type == OBJ_REF_DELTA)
404 resolve_delta(child, result, result_size, type);
405 }
53dda6ff
NP
406 }
407
408 memset(&delta_base, 0, sizeof(delta_base));
636171cb 409 delta_base.offset = delta_obj->offset;
b89c4e93 410 if (!find_delta_children(&delta_base, &first, &last)) {
636171cb
NP
411 for (j = first; j <= last; j++) {
412 struct object_entry *child = objects + deltas[j].obj_no;
413 if (child->real_type == OBJ_OFS_DELTA)
414 resolve_delta(child, result, result_size, type);
415 }
9cf6d335 416 }
53dda6ff 417
9cf6d335
SV
418 free(result);
419}
420
421static int compare_delta_entry(const void *a, const void *b)
422{
423 const struct delta_entry *delta_a = a;
424 const struct delta_entry *delta_b = b;
3c552873 425 return memcmp(&delta_a->base, &delta_b->base, UNION_BASE_SZ);
9cf6d335
SV
426}
427
2d477051
NP
428/* Parse all objects and return the pack content SHA1 hash */
429static void parse_pack_objects(unsigned char *sha1)
9cf6d335 430{
3c9af366 431 int i, percent = -1;
53dda6ff 432 struct delta_entry *delta = deltas;
9cf6d335 433 void *data;
2d477051 434 struct stat st;
9cf6d335
SV
435
436 /*
437 * First pass:
438 * - find locations of all objects;
439 * - calculate SHA1 of all non-delta objects;
b89c4e93 440 * - remember base (SHA1 or offset) for all deltas.
9cf6d335 441 */
3c9af366
NP
442 if (verbose)
443 fprintf(stderr, "Indexing %d objects.\n", nr_objects);
9cf6d335
SV
444 for (i = 0; i < nr_objects; i++) {
445 struct object_entry *obj = &objects[i];
2d477051 446 data = unpack_raw_entry(obj, &delta->base);
9cf6d335 447 obj->real_type = obj->type;
53dda6ff
NP
448 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
449 nr_deltas++;
636171cb 450 delta->obj_no = i;
53dda6ff 451 delta++;
9cf6d335 452 } else
9096c660 453 sha1_object(data, obj->size, obj->type, obj->sha1);
9cf6d335 454 free(data);
3c9af366
NP
455 if (verbose)
456 percent = display_progress(i+1, nr_objects, percent);
9cf6d335 457 }
2d477051 458 objects[i].offset = consumed_bytes;
3c9af366
NP
459 if (verbose)
460 fputc('\n', stderr);
2d477051
NP
461
462 /* Check pack integrity */
636171cb 463 flush();
2d477051
NP
464 SHA1_Final(sha1, &input_ctx);
465 if (hashcmp(fill(20), sha1))
e42797f5 466 die("pack is corrupted (SHA1 mismatch)");
9bee2478 467 use(20);
2d477051
NP
468
469 /* If input_fd is a file, we should have reached its end now. */
470 if (fstat(input_fd, &st))
e42797f5 471 die("cannot fstat packfile: %s", strerror(errno));
fa257b05
JS
472 if (S_ISREG(st.st_mode) &&
473 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
e42797f5 474 die("pack has junk at the end");
9cf6d335 475
3c9af366
NP
476 if (!nr_deltas)
477 return;
478
53dda6ff 479 /* Sort deltas by base SHA1/offset for fast searching */
9cf6d335
SV
480 qsort(deltas, nr_deltas, sizeof(struct delta_entry),
481 compare_delta_entry);
482
483 /*
484 * Second pass:
485 * - for all non-delta objects, look if it is used as a base for
486 * deltas;
487 * - if used as a base, uncompress the object and apply all deltas,
488 * recursively checking if the resulting object is used as a base
489 * for some more deltas.
490 */
3c9af366
NP
491 if (verbose)
492 fprintf(stderr, "Resolving %d deltas.\n", nr_deltas);
9cf6d335
SV
493 for (i = 0; i < nr_objects; i++) {
494 struct object_entry *obj = &objects[i];
53dda6ff
NP
495 union delta_base base;
496 int j, ref, ref_first, ref_last, ofs, ofs_first, ofs_last;
9cf6d335 497
53dda6ff 498 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA)
9cf6d335 499 continue;
53dda6ff 500 hashcpy(base.sha1, obj->sha1);
b89c4e93 501 ref = !find_delta_children(&base, &ref_first, &ref_last);
53dda6ff
NP
502 memset(&base, 0, sizeof(base));
503 base.offset = obj->offset;
b89c4e93 504 ofs = !find_delta_children(&base, &ofs_first, &ofs_last);
53dda6ff 505 if (!ref && !ofs)
9cf6d335 506 continue;
2d477051 507 data = get_data_from_pack(obj);
53dda6ff 508 if (ref)
636171cb
NP
509 for (j = ref_first; j <= ref_last; j++) {
510 struct object_entry *child = objects + deltas[j].obj_no;
511 if (child->real_type == OBJ_REF_DELTA)
512 resolve_delta(child, data,
2d477051 513 obj->size, obj->type);
636171cb 514 }
53dda6ff 515 if (ofs)
636171cb
NP
516 for (j = ofs_first; j <= ofs_last; j++) {
517 struct object_entry *child = objects + deltas[j].obj_no;
518 if (child->real_type == OBJ_OFS_DELTA)
519 resolve_delta(child, data,
2d477051 520 obj->size, obj->type);
636171cb 521 }
9cf6d335 522 free(data);
3c9af366
NP
523 if (verbose)
524 percent = display_progress(nr_resolved_deltas,
525 nr_deltas, percent);
9cf6d335 526 }
3c9af366
NP
527 if (verbose && nr_resolved_deltas == nr_deltas)
528 fputc('\n', stderr);
636171cb
NP
529}
530
ee5743ce 531static int write_compressed(int fd, void *in, unsigned int size, uint32_t *obj_crc)
636171cb
NP
532{
533 z_stream stream;
534 unsigned long maxsize;
535 void *out;
536
537 memset(&stream, 0, sizeof(stream));
538 deflateInit(&stream, zlib_compression_level);
539 maxsize = deflateBound(&stream, size);
540 out = xmalloc(maxsize);
541
542 /* Compress it */
543 stream.next_in = in;
544 stream.avail_in = size;
545 stream.next_out = out;
546 stream.avail_out = maxsize;
547 while (deflate(&stream, Z_FINISH) == Z_OK);
548 deflateEnd(&stream);
549
550 size = stream.total_out;
551 write_or_die(fd, out, size);
ee5743ce 552 *obj_crc = crc32(*obj_crc, out, size);
636171cb
NP
553 free(out);
554 return size;
555}
556
9096c660 557static void append_obj_to_pack(const unsigned char *sha1, void *buf,
636171cb
NP
558 unsigned long size, enum object_type type)
559{
560 struct object_entry *obj = &objects[nr_objects++];
561 unsigned char header[10];
562 unsigned long s = size;
563 int n = 0;
564 unsigned char c = (type << 4) | (s & 15);
565 s >>= 4;
566 while (s) {
567 header[n++] = c | 0x80;
568 c = s & 0x7f;
569 s >>= 7;
570 }
571 header[n++] = c;
572 write_or_die(output_fd, header, n);
ee5743ce
NP
573 obj[0].crc32 = crc32(0, Z_NULL, 0);
574 obj[0].crc32 = crc32(obj[0].crc32, header, n);
636171cb 575 obj[1].offset = obj[0].offset + n;
ee5743ce 576 obj[1].offset += write_compressed(output_fd, buf, size, &obj[0].crc32);
9096c660 577 hashcpy(obj->sha1, sha1);
636171cb
NP
578}
579
580static int delta_pos_compare(const void *_a, const void *_b)
581{
582 struct delta_entry *a = *(struct delta_entry **)_a;
583 struct delta_entry *b = *(struct delta_entry **)_b;
584 return a->obj_no - b->obj_no;
585}
9cf6d335 586
636171cb
NP
587static void fix_unresolved_deltas(int nr_unresolved)
588{
589 struct delta_entry **sorted_by_pos;
3c9af366 590 int i, n = 0, percent = -1;
636171cb
NP
591
592 /*
593 * Since many unresolved deltas may well be themselves base objects
594 * for more unresolved deltas, we really want to include the
595 * smallest number of base objects that would cover as much delta
596 * as possible by picking the
597 * trunc deltas first, allowing for other deltas to resolve without
598 * additional base objects. Since most base objects are to be found
599 * before deltas depending on them, a good heuristic is to start
600 * resolving deltas in the same order as their position in the pack.
601 */
602 sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
9cf6d335 603 for (i = 0; i < nr_deltas; i++) {
636171cb
NP
604 if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
605 continue;
606 sorted_by_pos[n++] = &deltas[i];
9cf6d335 607 }
636171cb
NP
608 qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
609
610 for (i = 0; i < n; i++) {
611 struct delta_entry *d = sorted_by_pos[i];
612 void *data;
613 unsigned long size;
21666f1a 614 enum object_type type;
636171cb
NP
615 int j, first, last;
616
617 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
618 continue;
21666f1a 619 data = read_sha1_file(d->base.sha1, &type, &size);
636171cb
NP
620 if (!data)
621 continue;
636171cb 622
b89c4e93 623 find_delta_children(&d->base, &first, &last);
636171cb
NP
624 for (j = first; j <= last; j++) {
625 struct object_entry *child = objects + deltas[j].obj_no;
626 if (child->real_type == OBJ_REF_DELTA)
21666f1a 627 resolve_delta(child, data, size, type);
636171cb
NP
628 }
629
9096c660
NP
630 if (check_sha1_signature(d->base.sha1, data, size, typename(type)))
631 die("local object %s is corrupt", sha1_to_hex(d->base.sha1));
632 append_obj_to_pack(d->base.sha1, data, size, type);
636171cb 633 free(data);
3c9af366
NP
634 if (verbose)
635 percent = display_progress(nr_resolved_deltas,
636 nr_deltas, percent);
636171cb
NP
637 }
638 free(sorted_by_pos);
3c9af366
NP
639 if (verbose)
640 fputc('\n', stderr);
636171cb
NP
641}
642
643static void readjust_pack_header_and_sha1(unsigned char *sha1)
644{
645 struct pack_header hdr;
646 SHA_CTX ctx;
647 int size;
648
649 /* Rewrite pack header with updated object number */
650 if (lseek(output_fd, 0, SEEK_SET) != 0)
651 die("cannot seek back: %s", strerror(errno));
93d26e4c 652 if (read_in_full(output_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
636171cb
NP
653 die("cannot read pack header back: %s", strerror(errno));
654 hdr.hdr_entries = htonl(nr_objects);
655 if (lseek(output_fd, 0, SEEK_SET) != 0)
656 die("cannot seek back: %s", strerror(errno));
657 write_or_die(output_fd, &hdr, sizeof(hdr));
658 if (lseek(output_fd, 0, SEEK_SET) != 0)
659 die("cannot seek back: %s", strerror(errno));
660
661 /* Recompute and store the new pack's SHA1 */
662 SHA1_Init(&ctx);
663 do {
664 unsigned char *buf[4096];
665 size = xread(output_fd, buf, sizeof(buf));
666 if (size < 0)
667 die("cannot read pack data back: %s", strerror(errno));
668 SHA1_Update(&ctx, buf, size);
669 } while (size > 0);
670 SHA1_Final(sha1, &ctx);
671 write_or_die(output_fd, sha1, 20);
9cf6d335
SV
672}
673
674static int sha1_compare(const void *_a, const void *_b)
675{
676 struct object_entry *a = *(struct object_entry **)_a;
677 struct object_entry *b = *(struct object_entry **)_b;
a89fccd2 678 return hashcmp(a->sha1, b->sha1);
9cf6d335
SV
679}
680
2d477051
NP
681/*
682 * On entry *sha1 contains the pack content SHA1 hash, on exit it is
683 * the SHA1 hash of sorted object names.
684 */
b89c4e93 685static const char *write_index_file(const char *index_name, unsigned char *sha1)
9cf6d335
SV
686{
687 struct sha1file *f;
7e4a2a84 688 struct object_entry **sorted_by_sha, **list, **last;
9cf6d335 689 unsigned int array[256];
e42797f5 690 int i, fd;
84c8d8ae 691 SHA_CTX ctx;
9cf6d335 692
7e4a2a84
JH
693 if (nr_objects) {
694 sorted_by_sha =
695 xcalloc(nr_objects, sizeof(struct object_entry *));
696 list = sorted_by_sha;
697 last = sorted_by_sha + nr_objects;
698 for (i = 0; i < nr_objects; ++i)
699 sorted_by_sha[i] = &objects[i];
700 qsort(sorted_by_sha, nr_objects, sizeof(sorted_by_sha[0]),
701 sha1_compare);
702
703 }
704 else
705 sorted_by_sha = list = last = NULL;
9cf6d335 706
e42797f5
NP
707 if (!index_name) {
708 static char tmpfile[PATH_MAX];
709 snprintf(tmpfile, sizeof(tmpfile),
0e55181f 710 "%s/tmp_idx_XXXXXX", get_object_directory());
e42797f5
NP
711 fd = mkstemp(tmpfile);
712 index_name = xstrdup(tmpfile);
713 } else {
714 unlink(index_name);
715 fd = open(index_name, O_CREAT|O_EXCL|O_WRONLY, 0600);
716 }
717 if (fd < 0)
718 die("unable to create %s: %s", index_name, strerror(errno));
719 f = sha1fd(fd, index_name);
9cf6d335
SV
720
721 /*
722 * Write the first-level table (the list is sorted,
723 * but we use a 256-entry lookup to be able to avoid
724 * having to do eight extra binary search iterations).
725 */
726 for (i = 0; i < 256; i++) {
727 struct object_entry **next = list;
728 while (next < last) {
729 struct object_entry *obj = *next;
730 if (obj->sha1[0] != i)
731 break;
732 next++;
733 }
734 array[i] = htonl(next - sorted_by_sha);
735 list = next;
736 }
737 sha1write(f, array, 256 * sizeof(int));
738
84c8d8ae
JH
739 /* recompute the SHA1 hash of sorted object names.
740 * currently pack-objects does not do this, but that
741 * can be fixed.
742 */
743 SHA1_Init(&ctx);
9cf6d335
SV
744 /*
745 * Write the actual SHA1 entries..
746 */
747 list = sorted_by_sha;
748 for (i = 0; i < nr_objects; i++) {
749 struct object_entry *obj = *list++;
750 unsigned int offset = htonl(obj->offset);
751 sha1write(f, &offset, 4);
752 sha1write(f, obj->sha1, 20);
84c8d8ae 753 SHA1_Update(&ctx, obj->sha1, 20);
9cf6d335 754 }
2d477051 755 sha1write(f, sha1, 20);
9cf6d335
SV
756 sha1close(f, NULL, 1);
757 free(sorted_by_sha);
84c8d8ae 758 SHA1_Final(sha1, &ctx);
e42797f5
NP
759 return index_name;
760}
761
762static void final(const char *final_pack_name, const char *curr_pack_name,
763 const char *final_index_name, const char *curr_index_name,
b8077709 764 const char *keep_name, const char *keep_msg,
e42797f5
NP
765 unsigned char *sha1)
766{
3a55602e 767 const char *report = "pack";
e42797f5
NP
768 char name[PATH_MAX];
769 int err;
770
771 if (!from_stdin) {
772 close(input_fd);
773 } else {
774 err = close(output_fd);
775 if (err)
776 die("error while closing pack file: %s", strerror(errno));
777 chmod(curr_pack_name, 0444);
778 }
779
b8077709
SP
780 if (keep_msg) {
781 int keep_fd, keep_msg_len = strlen(keep_msg);
782 if (!keep_name) {
783 snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
784 get_object_directory(), sha1_to_hex(sha1));
785 keep_name = name;
786 }
9ca4a201
NP
787 keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
788 if (keep_fd < 0) {
789 if (errno != EEXIST)
790 die("cannot write keep file");
791 } else {
792 if (keep_msg_len > 0) {
793 write_or_die(keep_fd, keep_msg, keep_msg_len);
794 write_or_die(keep_fd, "\n", 1);
795 }
796 close(keep_fd);
576162a4 797 report = "keep";
b8077709 798 }
b8077709
SP
799 }
800
e42797f5
NP
801 if (final_pack_name != curr_pack_name) {
802 if (!final_pack_name) {
803 snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
804 get_object_directory(), sha1_to_hex(sha1));
805 final_pack_name = name;
806 }
807 if (move_temp_to_file(curr_pack_name, final_pack_name))
808 die("cannot store pack file");
809 }
810
811 chmod(curr_index_name, 0444);
812 if (final_index_name != curr_index_name) {
813 if (!final_index_name) {
814 snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
815 get_object_directory(), sha1_to_hex(sha1));
816 final_index_name = name;
817 }
818 if (move_temp_to_file(curr_index_name, final_index_name))
819 die("cannot store index file");
820 }
576162a4
NP
821
822 if (!from_stdin) {
823 printf("%s\n", sha1_to_hex(sha1));
824 } else {
825 char buf[48];
826 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
827 report, sha1_to_hex(sha1));
d1b2ddc8 828 write_or_die(1, buf, len);
576162a4
NP
829
830 /*
831 * Let's just mimic git-unpack-objects here and write
832 * the last part of the input buffer to stdout.
833 */
834 while (input_len) {
835 err = xwrite(1, input_buffer + input_offset, input_len);
836 if (err <= 0)
837 break;
838 input_len -= err;
839 input_offset += err;
840 }
841 }
9cf6d335
SV
842}
843
844int main(int argc, char **argv)
845{
636171cb 846 int i, fix_thin_pack = 0;
e42797f5
NP
847 const char *curr_pack, *pack_name = NULL;
848 const char *curr_index, *index_name = NULL;
b8077709
SP
849 const char *keep_name = NULL, *keep_msg = NULL;
850 char *index_name_buf = NULL, *keep_name_buf = NULL;
84c8d8ae 851 unsigned char sha1[20];
9cf6d335
SV
852
853 for (i = 1; i < argc; i++) {
854 const char *arg = argv[i];
855
856 if (*arg == '-') {
e42797f5
NP
857 if (!strcmp(arg, "--stdin")) {
858 from_stdin = 1;
636171cb
NP
859 } else if (!strcmp(arg, "--fix-thin")) {
860 fix_thin_pack = 1;
b8077709
SP
861 } else if (!strcmp(arg, "--keep")) {
862 keep_msg = "";
cc44c765 863 } else if (!prefixcmp(arg, "--keep=")) {
b8077709 864 keep_msg = arg + 7;
cc44c765 865 } else if (!prefixcmp(arg, "--pack_header=")) {
bed006fb
NP
866 struct pack_header *hdr;
867 char *c;
868
869 hdr = (struct pack_header *)input_buffer;
870 hdr->hdr_signature = htonl(PACK_SIGNATURE);
871 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
872 if (*c != ',')
873 die("bad %s", arg);
874 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
875 if (*c)
876 die("bad %s", arg);
877 input_len = sizeof(*hdr);
3c9af366
NP
878 } else if (!strcmp(arg, "-v")) {
879 verbose = 1;
e42797f5 880 } else if (!strcmp(arg, "-o")) {
9cf6d335
SV
881 if (index_name || (i+1) >= argc)
882 usage(index_pack_usage);
883 index_name = argv[++i];
884 } else
885 usage(index_pack_usage);
886 continue;
887 }
888
889 if (pack_name)
890 usage(index_pack_usage);
891 pack_name = arg;
892 }
893
e42797f5 894 if (!pack_name && !from_stdin)
9cf6d335 895 usage(index_pack_usage);
636171cb
NP
896 if (fix_thin_pack && !from_stdin)
897 die("--fix-thin cannot be used without --stdin");
e42797f5 898 if (!index_name && pack_name) {
9cf6d335 899 int len = strlen(pack_name);
5bb1cda5 900 if (!has_extension(pack_name, ".pack"))
9cf6d335
SV
901 die("packfile name '%s' does not end with '.pack'",
902 pack_name);
6689f087 903 index_name_buf = xmalloc(len);
9cf6d335
SV
904 memcpy(index_name_buf, pack_name, len - 5);
905 strcpy(index_name_buf + len - 5, ".idx");
906 index_name = index_name_buf;
907 }
b8077709
SP
908 if (keep_msg && !keep_name && pack_name) {
909 int len = strlen(pack_name);
910 if (!has_extension(pack_name, ".pack"))
911 die("packfile name '%s' does not end with '.pack'",
912 pack_name);
913 keep_name_buf = xmalloc(len);
914 memcpy(keep_name_buf, pack_name, len - 5);
915 strcpy(keep_name_buf + len - 5, ".keep");
916 keep_name = keep_name_buf;
917 }
9cf6d335 918
e42797f5 919 curr_pack = open_pack_file(pack_name);
9cf6d335 920 parse_pack_header();
636171cb
NP
921 objects = xmalloc((nr_objects + 1) * sizeof(struct object_entry));
922 deltas = xmalloc(nr_objects * sizeof(struct delta_entry));
3c9af366
NP
923 if (verbose)
924 setup_progress_signal();
2d477051 925 parse_pack_objects(sha1);
636171cb
NP
926 if (nr_deltas != nr_resolved_deltas) {
927 if (fix_thin_pack) {
928 int nr_unresolved = nr_deltas - nr_resolved_deltas;
3c9af366 929 int nr_objects_initial = nr_objects;
636171cb
NP
930 if (nr_unresolved <= 0)
931 die("confusion beyond insanity");
932 objects = xrealloc(objects,
933 (nr_objects + nr_unresolved + 1)
934 * sizeof(*objects));
935 fix_unresolved_deltas(nr_unresolved);
3c9af366
NP
936 if (verbose)
937 fprintf(stderr, "%d objects were added to complete this thin pack.\n",
938 nr_objects - nr_objects_initial);
636171cb
NP
939 readjust_pack_header_and_sha1(sha1);
940 }
941 if (nr_deltas != nr_resolved_deltas)
942 die("pack has %d unresolved deltas",
943 nr_deltas - nr_resolved_deltas);
944 } else {
945 /* Flush remaining pack final 20-byte SHA1. */
636171cb
NP
946 flush();
947 }
9cf6d335 948 free(deltas);
e42797f5 949 curr_index = write_index_file(index_name, sha1);
b8077709
SP
950 final(pack_name, curr_pack,
951 index_name, curr_index,
952 keep_name, keep_msg,
953 sha1);
9cf6d335
SV
954 free(objects);
955 free(index_name_buf);
b8077709 956 free(keep_name_buf);
9cf6d335
SV
957
958 return 0;
959}