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