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