pack-objects: avoid delta chains that are too long.
[git.git] / pack-objects.c
1 #include "cache.h"
2 #include "object.h"
3 #include "delta.h"
4 #include "pack.h"
5 #include "csum-file.h"
6 #include <sys/time.h>
7
8 static const char pack_usage[] = "git-pack-objects [-q] [--no-reuse-delta] [--non-empty] [--local] [--incremental] [--window=N] [--depth=N] {--stdout | base-name} < object-list";
9
10 struct object_entry {
11         unsigned char sha1[20];
12         unsigned long size;     /* uncompressed size */
13         unsigned long offset;   /* offset into the final pack file;
14                                  * nonzero if already written.
15                                  */
16         unsigned int depth;     /* delta depth */
17         unsigned int delta_limit;       /* base adjustment for in-pack delta */
18         unsigned int hash;      /* name hint hash */
19         enum object_type type;
20         enum object_type in_pack_type;  /* could be delta */
21         unsigned long delta_size;       /* delta data size (uncompressed) */
22         struct object_entry *delta;     /* delta base object */
23         struct packed_git *in_pack;     /* already in pack */
24         unsigned int in_pack_offset;
25         struct object_entry *delta_child; /* delitified objects who bases me */
26         struct object_entry *delta_sibling; /* other deltified objects who
27                                              * uses the same base as me
28                                              */
29 };
30
31 /*
32  * Objects we are going to pack are colected in objects array (dynamically
33  * expanded).  nr_objects & nr_alloc controls this array.  They are stored
34  * in the order we see -- typically rev-list --objects order that gives us
35  * nice "minimum seek" order.
36  *
37  * sorted-by-sha ans sorted-by-type are arrays of pointers that point at
38  * elements in the objects array.  The former is used to build the pack
39  * index (lists object names in the ascending order to help offset lookup),
40  * and the latter is used to group similar things together by try_delta()
41  * heuristics.
42  */
43
44 static unsigned char object_list_sha1[20];
45 static int non_empty = 0;
46 static int no_reuse_delta = 0;
47 static int local = 0;
48 static int incremental = 0;
49 static struct object_entry **sorted_by_sha, **sorted_by_type;
50 static struct object_entry *objects = NULL;
51 static int nr_objects = 0, nr_alloc = 0;
52 static const char *base_name;
53 static unsigned char pack_file_sha1[20];
54 static int progress = 1;
55
56 /*
57  * The object names in objects array are hashed with this hashtable,
58  * to help looking up the entry by object name.  Binary search from
59  * sorted_by_sha is also possible but this was easier to code and faster.
60  * This hashtable is built after all the objects are seen.
61  */
62 static int *object_ix = NULL;
63 static int object_ix_hashsz = 0;
64
65 /*
66  * Pack index for existing packs give us easy access to the offsets into
67  * corresponding pack file where each object's data starts, but the entries
68  * do not store the size of the compressed representation (uncompressed
69  * size is easily available by examining the pack entry header).  We build
70  * a hashtable of existing packs (pack_revindex), and keep reverse index
71  * here -- pack index file is sorted by object name mapping to offset; this
72  * pack_revindex[].revindex array is an ordered list of offsets, so if you
73  * know the offset of an object, next offset is where its packed
74  * representation ends.
75  */
76 struct pack_revindex {
77         struct packed_git *p;
78         unsigned long *revindex;
79 } *pack_revindex = NULL;
80 static int pack_revindex_hashsz = 0;
81
82 /*
83  * stats
84  */
85 static int written = 0;
86 static int written_delta = 0;
87 static int reused = 0;
88 static int reused_delta = 0;
89
90 static int pack_revindex_ix(struct packed_git *p)
91 {
92         unsigned int ui = (unsigned int) p;
93         int i;
94
95         ui = ui ^ (ui >> 16); /* defeat structure alignment */
96         i = (int)(ui % pack_revindex_hashsz);
97         while (pack_revindex[i].p) {
98                 if (pack_revindex[i].p == p)
99                         return i;
100                 if (++i == pack_revindex_hashsz)
101                         i = 0;
102         }
103         return -1 - i;
104 }
105
106 static void prepare_pack_ix(void)
107 {
108         int num;
109         struct packed_git *p;
110         for (num = 0, p = packed_git; p; p = p->next)
111                 num++;
112         if (!num)
113                 return;
114         pack_revindex_hashsz = num * 11;
115         pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
116         for (p = packed_git; p; p = p->next) {
117                 num = pack_revindex_ix(p);
118                 num = - 1 - num;
119                 pack_revindex[num].p = p;
120         }
121         /* revindex elements are lazily initialized */
122 }
123
124 static int cmp_offset(const void *a_, const void *b_)
125 {
126         unsigned long a = *(unsigned long *) a_;
127         unsigned long b = *(unsigned long *) b_;
128         if (a < b)
129                 return -1;
130         else if (a == b)
131                 return 0;
132         else
133                 return 1;
134 }
135
136 /*
137  * Ordered list of offsets of objects in the pack.
138  */
139 static void prepare_pack_revindex(struct pack_revindex *rix)
140 {
141         struct packed_git *p = rix->p;
142         int num_ent = num_packed_objects(p);
143         int i;
144         void *index = p->index_base + 256;
145
146         rix->revindex = xmalloc(sizeof(unsigned long) * (num_ent + 1));
147         for (i = 0; i < num_ent; i++) {
148                 long hl = *((long *)(index + 24 * i));
149                 rix->revindex[i] = ntohl(hl);
150         }
151         /* This knows the pack format -- the 20-byte trailer
152          * follows immediately after the last object data.
153          */
154         rix->revindex[num_ent] = p->pack_size - 20;
155         qsort(rix->revindex, num_ent, sizeof(unsigned long), cmp_offset);
156 }
157
158 static unsigned long find_packed_object_size(struct packed_git *p,
159                                              unsigned long ofs)
160 {
161         int num;
162         int lo, hi;
163         struct pack_revindex *rix;
164         unsigned long *revindex;
165         num = pack_revindex_ix(p);
166         if (num < 0)
167                 die("internal error: pack revindex uninitialized");
168         rix = &pack_revindex[num];
169         if (!rix->revindex)
170                 prepare_pack_revindex(rix);
171         revindex = rix->revindex;
172         lo = 0;
173         hi = num_packed_objects(p) + 1;
174         do {
175                 int mi = (lo + hi) / 2;
176                 if (revindex[mi] == ofs) {
177                         return revindex[mi+1] - ofs;
178                 }
179                 else if (ofs < revindex[mi])
180                         hi = mi;
181                 else
182                         lo = mi + 1;
183         } while (lo < hi);
184         die("internal error: pack revindex corrupt");
185 }
186
187 static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
188 {
189         unsigned long othersize, delta_size;
190         char type[10];
191         void *otherbuf = read_sha1_file(entry->delta->sha1, type, &othersize);
192         void *delta_buf;
193
194         if (!otherbuf)
195                 die("unable to read %s", sha1_to_hex(entry->delta->sha1));
196         delta_buf = diff_delta(otherbuf, othersize,
197                                buf, size, &delta_size, 0);
198         if (!delta_buf || delta_size != entry->delta_size)
199                 die("delta size changed");
200         free(buf);
201         free(otherbuf);
202         return delta_buf;
203 }
204
205 /*
206  * The per-object header is a pretty dense thing, which is
207  *  - first byte: low four bits are "size", then three bits of "type",
208  *    and the high bit is "size continues".
209  *  - each byte afterwards: low seven bits are size continuation,
210  *    with the high bit being "size continues"
211  */
212 static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
213 {
214         int n = 1;
215         unsigned char c;
216
217         if (type < OBJ_COMMIT || type > OBJ_DELTA)
218                 die("bad type %d", type);
219
220         c = (type << 4) | (size & 15);
221         size >>= 4;
222         while (size) {
223                 *hdr++ = c | 0x80;
224                 c = size & 0x7f;
225                 size >>= 7;
226                 n++;
227         }
228         *hdr = c;
229         return n;
230 }
231
232 static unsigned long write_object(struct sha1file *f, struct object_entry *entry)
233 {
234         unsigned long size;
235         char type[10];
236         void *buf;
237         unsigned char header[10];
238         unsigned hdrlen, datalen;
239         enum object_type obj_type;
240         int to_reuse = 0;
241
242         obj_type = entry->type;
243         if (! entry->in_pack)
244                 to_reuse = 0;   /* can't reuse what we don't have */
245         else if (obj_type == OBJ_DELTA)
246                 to_reuse = 1;   /* check_object() decided it for us */
247         else if (obj_type != entry->in_pack_type)
248                 to_reuse = 0;   /* pack has delta which is unusable */
249         else if (entry->delta)
250                 to_reuse = 0;   /* we want to pack afresh */
251         else
252                 to_reuse = 1;   /* we have it in-pack undeltified,
253                                  * and we do not need to deltify it.
254                                  */
255
256         if (! to_reuse) {
257                 buf = read_sha1_file(entry->sha1, type, &size);
258                 if (!buf)
259                         die("unable to read %s", sha1_to_hex(entry->sha1));
260                 if (size != entry->size)
261                         die("object %s size inconsistency (%lu vs %lu)",
262                             sha1_to_hex(entry->sha1), size, entry->size);
263                 if (entry->delta) {
264                         buf = delta_against(buf, size, entry);
265                         size = entry->delta_size;
266                         obj_type = OBJ_DELTA;
267                 }
268                 /*
269                  * The object header is a byte of 'type' followed by zero or
270                  * more bytes of length.  For deltas, the 20 bytes of delta
271                  * sha1 follows that.
272                  */
273                 hdrlen = encode_header(obj_type, size, header);
274                 sha1write(f, header, hdrlen);
275
276                 if (entry->delta) {
277                         sha1write(f, entry->delta, 20);
278                         hdrlen += 20;
279                 }
280                 datalen = sha1write_compressed(f, buf, size);
281                 free(buf);
282         }
283         else {
284                 struct packed_git *p = entry->in_pack;
285                 use_packed_git(p);
286
287                 datalen = find_packed_object_size(p, entry->in_pack_offset);
288                 buf = p->pack_base + entry->in_pack_offset;
289                 sha1write(f, buf, datalen);
290                 unuse_packed_git(p);
291                 hdrlen = 0; /* not really */
292                 if (obj_type == OBJ_DELTA)
293                         reused_delta++;
294                 reused++;
295         }
296         if (obj_type == OBJ_DELTA)
297                 written_delta++;
298         written++;
299         return hdrlen + datalen;
300 }
301
302 static unsigned long write_one(struct sha1file *f,
303                                struct object_entry *e,
304                                unsigned long offset)
305 {
306         if (e->offset)
307                 /* offset starts from header size and cannot be zero
308                  * if it is written already.
309                  */
310                 return offset;
311         e->offset = offset;
312         offset += write_object(f, e);
313         /* if we are deltified, write out its base object. */
314         if (e->delta)
315                 offset = write_one(f, e->delta, offset);
316         return offset;
317 }
318
319 static void write_pack_file(void)
320 {
321         int i;
322         struct sha1file *f;
323         unsigned long offset;
324         struct pack_header hdr;
325
326         if (!base_name)
327                 f = sha1fd(1, "<stdout>");
328         else
329                 f = sha1create("%s-%s.%s", base_name, sha1_to_hex(object_list_sha1), "pack");
330         hdr.hdr_signature = htonl(PACK_SIGNATURE);
331         hdr.hdr_version = htonl(PACK_VERSION);
332         hdr.hdr_entries = htonl(nr_objects);
333         sha1write(f, &hdr, sizeof(hdr));
334         offset = sizeof(hdr);
335         for (i = 0; i < nr_objects; i++)
336                 offset = write_one(f, objects + i, offset);
337
338         sha1close(f, pack_file_sha1, 1);
339 }
340
341 static void write_index_file(void)
342 {
343         int i;
344         struct sha1file *f = sha1create("%s-%s.%s", base_name, sha1_to_hex(object_list_sha1), "idx");
345         struct object_entry **list = sorted_by_sha;
346         struct object_entry **last = list + nr_objects;
347         unsigned int array[256];
348
349         /*
350          * Write the first-level table (the list is sorted,
351          * but we use a 256-entry lookup to be able to avoid
352          * having to do eight extra binary search iterations).
353          */
354         for (i = 0; i < 256; i++) {
355                 struct object_entry **next = list;
356                 while (next < last) {
357                         struct object_entry *entry = *next;
358                         if (entry->sha1[0] != i)
359                                 break;
360                         next++;
361                 }
362                 array[i] = htonl(next - sorted_by_sha);
363                 list = next;
364         }
365         sha1write(f, array, 256 * sizeof(int));
366
367         /*
368          * Write the actual SHA1 entries..
369          */
370         list = sorted_by_sha;
371         for (i = 0; i < nr_objects; i++) {
372                 struct object_entry *entry = *list++;
373                 unsigned int offset = htonl(entry->offset);
374                 sha1write(f, &offset, 4);
375                 sha1write(f, entry->sha1, 20);
376         }
377         sha1write(f, pack_file_sha1, 20);
378         sha1close(f, NULL, 1);
379 }
380
381 static int add_object_entry(unsigned char *sha1, unsigned int hash)
382 {
383         unsigned int idx = nr_objects;
384         struct object_entry *entry;
385         struct packed_git *p;
386         unsigned int found_offset = 0;
387         struct packed_git *found_pack = NULL;
388
389         for (p = packed_git; p; p = p->next) {
390                 struct pack_entry e;
391                 if (find_pack_entry_one(sha1, &e, p)) {
392                         if (incremental)
393                                 return 0;
394                         if (local && !p->pack_local)
395                                 return 0;
396                         if (!found_pack) {
397                                 found_offset = e.offset;
398                                 found_pack = e.p;
399                         }
400                 }
401         }
402
403         if (idx >= nr_alloc) {
404                 unsigned int needed = (idx + 1024) * 3 / 2;
405                 objects = xrealloc(objects, needed * sizeof(*entry));
406                 nr_alloc = needed;
407         }
408         entry = objects + idx;
409         memset(entry, 0, sizeof(*entry));
410         memcpy(entry->sha1, sha1, 20);
411         entry->hash = hash;
412         if (found_pack) {
413                 entry->in_pack = found_pack;
414                 entry->in_pack_offset = found_offset;
415         }
416         nr_objects = idx+1;
417         return 1;
418 }
419
420 static int locate_object_entry_hash(unsigned char *sha1)
421 {
422         int i;
423         unsigned int ui;
424         memcpy(&ui, sha1, sizeof(unsigned int));
425         i = ui % object_ix_hashsz;
426         while (0 < object_ix[i]) {
427                 if (!memcmp(sha1, objects[object_ix[i]-1].sha1, 20))
428                         return i;
429                 if (++i == object_ix_hashsz)
430                         i = 0;
431         }
432         return -1 - i;
433 }
434
435 static struct object_entry *locate_object_entry(unsigned char *sha1)
436 {
437         int i = locate_object_entry_hash(sha1);
438         if (0 <= i)
439                 return &objects[object_ix[i]-1];
440         return NULL;
441 }
442
443 static void check_object(struct object_entry *entry)
444 {
445         char type[20];
446
447         if (entry->in_pack) {
448                 unsigned char base[20];
449                 unsigned long size;
450                 struct object_entry *base_entry;
451
452                 /* We want in_pack_type even if we do not reuse delta.
453                  * There is no point not reusing non-delta representations.
454                  */
455                 check_reuse_pack_delta(entry->in_pack,
456                                        entry->in_pack_offset,
457                                        base, &size,
458                                        &entry->in_pack_type);
459
460                 /* Check if it is delta, and the base is also an object
461                  * we are going to pack.  If so we will reuse the existing
462                  * delta.
463                  */
464                 if (!no_reuse_delta &&
465                     entry->in_pack_type == OBJ_DELTA &&
466                     (base_entry = locate_object_entry(base))) {
467
468                         /* Depth value does not matter - find_deltas()
469                          * will never consider reused delta as the
470                          * base object to deltify other objects
471                          * against, in order to avoid circular deltas.
472                          */
473
474                         /* uncompressed size of the delta data */
475                         entry->size = entry->delta_size = size;
476                         entry->delta = base_entry;
477                         entry->type = OBJ_DELTA;
478
479                         entry->delta_sibling = base_entry->delta_child;
480                         base_entry->delta_child = entry;
481
482                         return;
483                 }
484                 /* Otherwise we would do the usual */
485         }
486
487         if (sha1_object_info(entry->sha1, type, &entry->size))
488                 die("unable to get type of object %s",
489                     sha1_to_hex(entry->sha1));
490
491         if (!strcmp(type, "commit")) {
492                 entry->type = OBJ_COMMIT;
493         } else if (!strcmp(type, "tree")) {
494                 entry->type = OBJ_TREE;
495         } else if (!strcmp(type, "blob")) {
496                 entry->type = OBJ_BLOB;
497         } else if (!strcmp(type, "tag")) {
498                 entry->type = OBJ_TAG;
499         } else
500                 die("unable to pack object %s of type %s",
501                     sha1_to_hex(entry->sha1), type);
502 }
503
504 static void hash_objects(void)
505 {
506         int i;
507         struct object_entry *oe;
508
509         object_ix_hashsz = nr_objects * 2;
510         object_ix = xcalloc(sizeof(int), object_ix_hashsz);
511         for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
512                 int ix = locate_object_entry_hash(oe->sha1);
513                 if (0 <= ix) {
514                         error("the same object '%s' added twice",
515                               sha1_to_hex(oe->sha1));
516                         continue;
517                 }
518                 ix = -1 - ix;
519                 object_ix[ix] = i + 1;
520         }
521 }
522
523 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
524 {
525         struct object_entry *child = me->delta_child;
526         unsigned int m = n;
527         while (child) {
528                 unsigned int c = check_delta_limit(child, n + 1);
529                 if (m < c)
530                         m = c;
531                 child = child->delta_sibling;
532         }
533         return m;
534 }
535
536 static void get_object_details(void)
537 {
538         int i;
539         struct object_entry *entry;
540
541         hash_objects();
542         prepare_pack_ix();
543         for (i = 0, entry = objects; i < nr_objects; i++, entry++)
544                 check_object(entry);
545         for (i = 0, entry = objects; i < nr_objects; i++, entry++)
546                 if (!entry->delta && entry->delta_child)
547                         entry->delta_limit =
548                                 check_delta_limit(entry, 1);
549 }
550
551 typedef int (*entry_sort_t)(const struct object_entry *, const struct object_entry *);
552
553 static entry_sort_t current_sort;
554
555 static int sort_comparator(const void *_a, const void *_b)
556 {
557         struct object_entry *a = *(struct object_entry **)_a;
558         struct object_entry *b = *(struct object_entry **)_b;
559         return current_sort(a,b);
560 }
561
562 static struct object_entry **create_sorted_list(entry_sort_t sort)
563 {
564         struct object_entry **list = xmalloc(nr_objects * sizeof(struct object_entry *));
565         int i;
566
567         for (i = 0; i < nr_objects; i++)
568                 list[i] = objects + i;
569         current_sort = sort;
570         qsort(list, nr_objects, sizeof(struct object_entry *), sort_comparator);
571         return list;
572 }
573
574 static int sha1_sort(const struct object_entry *a, const struct object_entry *b)
575 {
576         return memcmp(a->sha1, b->sha1, 20);
577 }
578
579 static int type_size_sort(const struct object_entry *a, const struct object_entry *b)
580 {
581         if (a->type < b->type)
582                 return -1;
583         if (a->type > b->type)
584                 return 1;
585         if (a->hash < b->hash)
586                 return -1;
587         if (a->hash > b->hash)
588                 return 1;
589         if (a->size < b->size)
590                 return -1;
591         if (a->size > b->size)
592                 return 1;
593         return a < b ? -1 : (a > b);
594 }
595
596 struct unpacked {
597         struct object_entry *entry;
598         void *data;
599 };
600
601 /*
602  * We search for deltas _backwards_ in a list sorted by type and
603  * by size, so that we see progressively smaller and smaller files.
604  * That's because we prefer deltas to be from the bigger file
605  * to the smaller - deletes are potentially cheaper, but perhaps
606  * more importantly, the bigger file is likely the more recent
607  * one.
608  */
609 static int try_delta(struct unpacked *cur, struct unpacked *old, unsigned max_depth)
610 {
611         struct object_entry *cur_entry = cur->entry;
612         struct object_entry *old_entry = old->entry;
613         unsigned long size, oldsize, delta_size, sizediff;
614         long max_size;
615         void *delta_buf;
616
617         /* Don't bother doing diffs between different types */
618         if (cur_entry->type != old_entry->type)
619                 return -1;
620
621         /* If the current object is at edge, take the depth the objects
622          * that depend on the current object into account -- otherwise
623          * they would become too deep.
624          */
625         if (cur_entry->delta_child) {
626                 if (max_depth <= cur_entry->delta_limit)
627                         return 0;
628                 max_depth -= cur_entry->delta_limit;
629         }
630
631         size = cur_entry->size;
632         if (size < 50)
633                 return -1;
634         oldsize = old_entry->size;
635         sizediff = oldsize > size ? oldsize - size : size - oldsize;
636         if (sizediff > size / 8)
637                 return -1;
638         if (old_entry->depth >= max_depth)
639                 return 0;
640
641         /*
642          * NOTE!
643          *
644          * We always delta from the bigger to the smaller, since that's
645          * more space-efficient (deletes don't have to say _what_ they
646          * delete).
647          */
648         max_size = size / 2 - 20;
649         if (cur_entry->delta)
650                 max_size = cur_entry->delta_size-1;
651         if (sizediff >= max_size)
652                 return -1;
653         delta_buf = diff_delta(old->data, oldsize,
654                                cur->data, size, &delta_size, max_size);
655         if (!delta_buf)
656                 return 0;
657         cur_entry->delta = old_entry;
658         cur_entry->delta_size = delta_size;
659         cur_entry->depth = old_entry->depth + 1;
660         free(delta_buf);
661         return 0;
662 }
663
664 static void find_deltas(struct object_entry **list, int window, int depth)
665 {
666         int i, idx;
667         unsigned int array_size = window * sizeof(struct unpacked);
668         struct unpacked *array = xmalloc(array_size);
669         int eye_candy;
670
671         memset(array, 0, array_size);
672         i = nr_objects;
673         idx = 0;
674         eye_candy = i - (nr_objects / 20);
675
676         while (--i >= 0) {
677                 struct object_entry *entry = list[i];
678                 struct unpacked *n = array + idx;
679                 unsigned long size;
680                 char type[10];
681                 int j;
682
683                 if (progress && i <= eye_candy) {
684                         eye_candy -= nr_objects / 20;
685                         fputc('.', stderr);
686                 }
687
688                 if (entry->delta)
689                         /* This happens if we decided to reuse existing
690                          * delta from a pack.  "!no_reuse_delta &&" is implied.
691                          */
692                         continue;
693
694                 free(n->data);
695                 n->entry = entry;
696                 n->data = read_sha1_file(entry->sha1, type, &size);
697                 if (size != entry->size)
698                         die("object %s inconsistent object length (%lu vs %lu)", sha1_to_hex(entry->sha1), size, entry->size);
699
700                 j = window;
701                 while (--j > 0) {
702                         unsigned int other_idx = idx + j;
703                         struct unpacked *m;
704                         if (other_idx >= window)
705                                 other_idx -= window;
706                         m = array + other_idx;
707                         if (!m->entry)
708                                 break;
709                         if (try_delta(n, m, depth) < 0)
710                                 break;
711                 }
712                 idx++;
713                 if (idx >= window)
714                         idx = 0;
715         }
716
717         for (i = 0; i < window; ++i)
718                 free(array[i].data);
719         free(array);
720 }
721
722 static void prepare_pack(int window, int depth)
723 {
724         if (progress)
725                 fprintf(stderr, "Packing %d objects", nr_objects);
726         get_object_details();
727         if (progress)
728                 fputc('.', stderr);
729
730         sorted_by_type = create_sorted_list(type_size_sort);
731         if (window && depth)
732                 find_deltas(sorted_by_type, window+1, depth);
733         if (progress)
734                 fputc('\n', stderr);
735         write_pack_file();
736 }
737
738 static int reuse_cached_pack(unsigned char *sha1, int pack_to_stdout)
739 {
740         static const char cache[] = "pack-cache/pack-%s.%s";
741         char *cached_pack, *cached_idx;
742         int ifd, ofd, ifd_ix = -1;
743
744         cached_pack = git_path(cache, sha1_to_hex(sha1), "pack");
745         ifd = open(cached_pack, O_RDONLY);
746         if (ifd < 0)
747                 return 0;
748
749         if (!pack_to_stdout) {
750                 cached_idx = git_path(cache, sha1_to_hex(sha1), "idx");
751                 ifd_ix = open(cached_idx, O_RDONLY);
752                 if (ifd_ix < 0) {
753                         close(ifd);
754                         return 0;
755                 }
756         }
757
758         if (progress)
759                 fprintf(stderr, "Reusing %d objects pack %s\n", nr_objects,
760                         sha1_to_hex(sha1));
761
762         if (pack_to_stdout) {
763                 if (copy_fd(ifd, 1))
764                         exit(1);
765                 close(ifd);
766         }
767         else {
768                 char name[PATH_MAX];
769                 snprintf(name, sizeof(name),
770                          "%s-%s.%s", base_name, sha1_to_hex(sha1), "pack");
771                 ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
772                 if (ofd < 0)
773                         die("unable to open %s (%s)", name, strerror(errno));
774                 if (copy_fd(ifd, ofd))
775                         exit(1);
776                 close(ifd);
777
778                 snprintf(name, sizeof(name),
779                          "%s-%s.%s", base_name, sha1_to_hex(sha1), "idx");
780                 ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
781                 if (ofd < 0)
782                         die("unable to open %s (%s)", name, strerror(errno));
783                 if (copy_fd(ifd_ix, ofd))
784                         exit(1);
785                 close(ifd_ix);
786                 puts(sha1_to_hex(sha1));
787         }
788
789         return 1;
790 }
791
792 int main(int argc, char **argv)
793 {
794         SHA_CTX ctx;
795         char line[PATH_MAX + 20];
796         int window = 10, depth = 10, pack_to_stdout = 0;
797         struct object_entry **list;
798         int i;
799         struct timeval prev_tv;
800         int eye_candy = 0;
801         int eye_candy_incr = 500;
802
803
804         setup_git_directory();
805
806         for (i = 1; i < argc; i++) {
807                 const char *arg = argv[i];
808
809                 if (*arg == '-') {
810                         if (!strcmp("--non-empty", arg)) {
811                                 non_empty = 1;
812                                 continue;
813                         }
814                         if (!strcmp("--local", arg)) {
815                                 local = 1;
816                                 continue;
817                         }
818                         if (!strcmp("--incremental", arg)) {
819                                 incremental = 1;
820                                 continue;
821                         }
822                         if (!strncmp("--window=", arg, 9)) {
823                                 char *end;
824                                 window = strtoul(arg+9, &end, 0);
825                                 if (!arg[9] || *end)
826                                         usage(pack_usage);
827                                 continue;
828                         }
829                         if (!strncmp("--depth=", arg, 8)) {
830                                 char *end;
831                                 depth = strtoul(arg+8, &end, 0);
832                                 if (!arg[8] || *end)
833                                         usage(pack_usage);
834                                 continue;
835                         }
836                         if (!strcmp("-q", arg)) {
837                                 progress = 0;
838                                 continue;
839                         }
840                         if (!strcmp("--no-reuse-delta", arg)) {
841                                 no_reuse_delta = 1;
842                                 continue;
843                         }
844                         if (!strcmp("--stdout", arg)) {
845                                 pack_to_stdout = 1;
846                                 continue;
847                         }
848                         usage(pack_usage);
849                 }
850                 if (base_name)
851                         usage(pack_usage);
852                 base_name = arg;
853         }
854
855         if (pack_to_stdout != !base_name)
856                 usage(pack_usage);
857
858         prepare_packed_git();
859         if (progress) {
860                 fprintf(stderr, "Generating pack...\n");
861                 gettimeofday(&prev_tv, NULL);
862         }
863         while (fgets(line, sizeof(line), stdin) != NULL) {
864                 unsigned int hash;
865                 char *p;
866                 unsigned char sha1[20];
867
868                 if (progress && (eye_candy <= nr_objects)) {
869                         fprintf(stderr, "Counting objects...%d\r", nr_objects);
870                         if (eye_candy && (50 <= eye_candy_incr)) {
871                                 struct timeval tv;
872                                 int time_diff;
873                                 gettimeofday(&tv, NULL);
874                                 time_diff = (tv.tv_sec - prev_tv.tv_sec);
875                                 time_diff <<= 10;
876                                 time_diff += (tv.tv_usec - prev_tv.tv_usec);
877                                 if ((1 << 9) < time_diff)
878                                         eye_candy_incr += 50;
879                                 else if (50 < eye_candy_incr)
880                                         eye_candy_incr -= 50;
881                         }
882                         eye_candy += eye_candy_incr;
883                 }
884                 if (get_sha1_hex(line, sha1))
885                         die("expected sha1, got garbage:\n %s", line);
886                 hash = 0;
887                 p = line+40;
888                 while (*p) {
889                         unsigned char c = *p++;
890                         if (isspace(c))
891                                 continue;
892                         hash = hash * 11 + c;
893                 }
894                 add_object_entry(sha1, hash);
895         }
896         if (progress)
897                 fprintf(stderr, "Done counting %d objects.\n", nr_objects);
898         if (non_empty && !nr_objects)
899                 return 0;
900
901         sorted_by_sha = create_sorted_list(sha1_sort);
902         SHA1_Init(&ctx);
903         list = sorted_by_sha;
904         for (i = 0; i < nr_objects; i++) {
905                 struct object_entry *entry = *list++;
906                 SHA1_Update(&ctx, entry->sha1, 20);
907         }
908         SHA1_Final(object_list_sha1, &ctx);
909
910         if (reuse_cached_pack(object_list_sha1, pack_to_stdout))
911                 ;
912         else {
913                 prepare_pack(window, depth);
914                 if (!pack_to_stdout) {
915                         write_index_file();
916                         puts(sha1_to_hex(object_list_sha1));
917                 }
918         }
919         if (progress)
920                 fprintf(stderr, "Total %d, written %d (delta %d), reused %d (delta %d)\n",
921                         nr_objects, written, written_delta, reused, reused_delta);
922         return 0;
923 }