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