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