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