pack-objects: run rev-list equivalent internally.
[git] / builtin-pack-objects.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "object.h"
4 #include "blob.h"
5 #include "commit.h"
6 #include "tag.h"
7 #include "tree.h"
8 #include "delta.h"
9 #include "pack.h"
10 #include "csum-file.h"
11 #include "tree-walk.h"
12 #include "diff.h"
13 #include "revision.h"
14 #include "list-objects.h"
15 #include <sys/time.h>
16 #include <signal.h>
17
18 static const char pack_usage[] = "git-pack-objects [-q] [--no-reuse-delta] [--non-empty] [--local] [--incremental] [--window=N] [--depth=N] {--stdout | base-name} [--revs [--unpacked | --all]* <ref-list | <object-list]";
19
20 struct object_entry {
21         unsigned char sha1[20];
22         unsigned long size;     /* uncompressed size */
23         unsigned long offset;   /* offset into the final pack file;
24                                  * nonzero if already written.
25                                  */
26         unsigned int depth;     /* delta depth */
27         unsigned int delta_limit;       /* base adjustment for in-pack delta */
28         unsigned int hash;      /* name hint hash */
29         enum object_type type;
30         enum object_type in_pack_type;  /* could be delta */
31         unsigned long delta_size;       /* delta data size (uncompressed) */
32         struct object_entry *delta;     /* delta base object */
33         struct packed_git *in_pack;     /* already in pack */
34         unsigned int in_pack_offset;
35         struct object_entry *delta_child; /* deltified objects who bases me */
36         struct object_entry *delta_sibling; /* other deltified objects who
37                                              * uses the same base as me
38                                              */
39         int preferred_base;     /* we do not pack this, but is encouraged to
40                                  * be used as the base objectto delta huge
41                                  * objects against.
42                                  */
43 };
44
45 /*
46  * Objects we are going to pack are collected in objects array (dynamically
47  * expanded).  nr_objects & nr_alloc controls this array.  They are stored
48  * in the order we see -- typically rev-list --objects order that gives us
49  * nice "minimum seek" order.
50  *
51  * sorted-by-sha ans sorted-by-type are arrays of pointers that point at
52  * elements in the objects array.  The former is used to build the pack
53  * index (lists object names in the ascending order to help offset lookup),
54  * and the latter is used to group similar things together by try_delta()
55  * heuristics.
56  */
57
58 static unsigned char object_list_sha1[20];
59 static int non_empty;
60 static int no_reuse_delta;
61 static int local;
62 static int incremental;
63 static struct object_entry **sorted_by_sha, **sorted_by_type;
64 static struct object_entry *objects;
65 static int nr_objects, nr_alloc, nr_result;
66 static const char *base_name;
67 static unsigned char pack_file_sha1[20];
68 static int progress = 1;
69 static volatile sig_atomic_t progress_update;
70 static int window = 10;
71 static int pack_to_stdout;
72
73 /*
74  * The object names in objects array are hashed with this hashtable,
75  * to help looking up the entry by object name.  Binary search from
76  * sorted_by_sha is also possible but this was easier to code and faster.
77  * This hashtable is built after all the objects are seen.
78  */
79 static int *object_ix;
80 static int object_ix_hashsz;
81
82 /*
83  * Pack index for existing packs give us easy access to the offsets into
84  * corresponding pack file where each object's data starts, but the entries
85  * do not store the size of the compressed representation (uncompressed
86  * size is easily available by examining the pack entry header).  We build
87  * a hashtable of existing packs (pack_revindex), and keep reverse index
88  * here -- pack index file is sorted by object name mapping to offset; this
89  * pack_revindex[].revindex array is an ordered list of offsets, so if you
90  * know the offset of an object, next offset is where its packed
91  * representation ends.
92  */
93 struct pack_revindex {
94         struct packed_git *p;
95         unsigned long *revindex;
96 } *pack_revindex = NULL;
97 static int pack_revindex_hashsz;
98
99 /*
100  * stats
101  */
102 static int written;
103 static int written_delta;
104 static int reused;
105 static int reused_delta;
106
107 static int pack_revindex_ix(struct packed_git *p)
108 {
109         unsigned long ui = (unsigned long)p;
110         int i;
111
112         ui = ui ^ (ui >> 16); /* defeat structure alignment */
113         i = (int)(ui % pack_revindex_hashsz);
114         while (pack_revindex[i].p) {
115                 if (pack_revindex[i].p == p)
116                         return i;
117                 if (++i == pack_revindex_hashsz)
118                         i = 0;
119         }
120         return -1 - i;
121 }
122
123 static void prepare_pack_ix(void)
124 {
125         int num;
126         struct packed_git *p;
127         for (num = 0, p = packed_git; p; p = p->next)
128                 num++;
129         if (!num)
130                 return;
131         pack_revindex_hashsz = num * 11;
132         pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
133         for (p = packed_git; p; p = p->next) {
134                 num = pack_revindex_ix(p);
135                 num = - 1 - num;
136                 pack_revindex[num].p = p;
137         }
138         /* revindex elements are lazily initialized */
139 }
140
141 static int cmp_offset(const void *a_, const void *b_)
142 {
143         unsigned long a = *(unsigned long *) a_;
144         unsigned long b = *(unsigned long *) b_;
145         if (a < b)
146                 return -1;
147         else if (a == b)
148                 return 0;
149         else
150                 return 1;
151 }
152
153 /*
154  * Ordered list of offsets of objects in the pack.
155  */
156 static void prepare_pack_revindex(struct pack_revindex *rix)
157 {
158         struct packed_git *p = rix->p;
159         int num_ent = num_packed_objects(p);
160         int i;
161         void *index = p->index_base + 256;
162
163         rix->revindex = xmalloc(sizeof(unsigned long) * (num_ent + 1));
164         for (i = 0; i < num_ent; i++) {
165                 unsigned int hl = *((unsigned int *)((char *) index + 24*i));
166                 rix->revindex[i] = ntohl(hl);
167         }
168         /* This knows the pack format -- the 20-byte trailer
169          * follows immediately after the last object data.
170          */
171         rix->revindex[num_ent] = p->pack_size - 20;
172         qsort(rix->revindex, num_ent, sizeof(unsigned long), cmp_offset);
173 }
174
175 static unsigned long find_packed_object_size(struct packed_git *p,
176                                              unsigned long ofs)
177 {
178         int num;
179         int lo, hi;
180         struct pack_revindex *rix;
181         unsigned long *revindex;
182         num = pack_revindex_ix(p);
183         if (num < 0)
184                 die("internal error: pack revindex uninitialized");
185         rix = &pack_revindex[num];
186         if (!rix->revindex)
187                 prepare_pack_revindex(rix);
188         revindex = rix->revindex;
189         lo = 0;
190         hi = num_packed_objects(p) + 1;
191         do {
192                 int mi = (lo + hi) / 2;
193                 if (revindex[mi] == ofs) {
194                         return revindex[mi+1] - ofs;
195                 }
196                 else if (ofs < revindex[mi])
197                         hi = mi;
198                 else
199                         lo = mi + 1;
200         } while (lo < hi);
201         die("internal error: pack revindex corrupt");
202 }
203
204 static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
205 {
206         unsigned long othersize, delta_size;
207         char type[10];
208         void *otherbuf = read_sha1_file(entry->delta->sha1, type, &othersize);
209         void *delta_buf;
210
211         if (!otherbuf)
212                 die("unable to read %s", sha1_to_hex(entry->delta->sha1));
213         delta_buf = diff_delta(otherbuf, othersize,
214                                buf, size, &delta_size, 0);
215         if (!delta_buf || delta_size != entry->delta_size)
216                 die("delta size changed");
217         free(buf);
218         free(otherbuf);
219         return delta_buf;
220 }
221
222 /*
223  * The per-object header is a pretty dense thing, which is
224  *  - first byte: low four bits are "size", then three bits of "type",
225  *    and the high bit is "size continues".
226  *  - each byte afterwards: low seven bits are size continuation,
227  *    with the high bit being "size continues"
228  */
229 static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
230 {
231         int n = 1;
232         unsigned char c;
233
234         if (type < OBJ_COMMIT || type > OBJ_DELTA)
235                 die("bad type %d", type);
236
237         c = (type << 4) | (size & 15);
238         size >>= 4;
239         while (size) {
240                 *hdr++ = c | 0x80;
241                 c = size & 0x7f;
242                 size >>= 7;
243                 n++;
244         }
245         *hdr = c;
246         return n;
247 }
248
249 static int check_inflate(unsigned char *data, unsigned long len, unsigned long expect)
250 {
251         z_stream stream;
252         unsigned char fakebuf[4096];
253         int st;
254
255         memset(&stream, 0, sizeof(stream));
256         stream.next_in = data;
257         stream.avail_in = len;
258         stream.next_out = fakebuf;
259         stream.avail_out = sizeof(fakebuf);
260         inflateInit(&stream);
261
262         while (1) {
263                 st = inflate(&stream, Z_FINISH);
264                 if (st == Z_STREAM_END || st == Z_OK) {
265                         st = (stream.total_out == expect &&
266                               stream.total_in == len) ? 0 : -1;
267                         break;
268                 }
269                 if (st != Z_BUF_ERROR) {
270                         st = -1;
271                         break;
272                 }
273                 stream.next_out = fakebuf;
274                 stream.avail_out = sizeof(fakebuf);
275         }
276         inflateEnd(&stream);
277         return st;
278 }
279
280 /*
281  * we are going to reuse the existing pack entry data.  make
282  * sure it is not corrupt.
283  */
284 static int revalidate_pack_entry(struct object_entry *entry, unsigned char *data, unsigned long len)
285 {
286         enum object_type type;
287         unsigned long size, used;
288
289         if (pack_to_stdout)
290                 return 0;
291
292         /* the caller has already called use_packed_git() for us,
293          * so it is safe to access the pack data from mmapped location.
294          * make sure the entry inflates correctly.
295          */
296         used = unpack_object_header_gently(data, len, &type, &size);
297         if (!used)
298                 return -1;
299         if (type == OBJ_DELTA)
300                 used += 20; /* skip base object name */
301         data += used;
302         len -= used;
303         return check_inflate(data, len, entry->size);
304 }
305
306 static int revalidate_loose_object(struct object_entry *entry,
307                                    unsigned char *map,
308                                    unsigned long mapsize)
309 {
310         /* we already know this is a loose object with new type header. */
311         enum object_type type;
312         unsigned long size, used;
313
314         if (pack_to_stdout)
315                 return 0;
316
317         used = unpack_object_header_gently(map, mapsize, &type, &size);
318         if (!used)
319                 return -1;
320         map += used;
321         mapsize -= used;
322         return check_inflate(map, mapsize, size);
323 }
324
325 static unsigned long write_object(struct sha1file *f,
326                                   struct object_entry *entry)
327 {
328         unsigned long size;
329         char type[10];
330         void *buf;
331         unsigned char header[10];
332         unsigned hdrlen, datalen;
333         enum object_type obj_type;
334         int to_reuse = 0;
335
336         if (entry->preferred_base)
337                 return 0;
338
339         obj_type = entry->type;
340         if (! entry->in_pack)
341                 to_reuse = 0;   /* can't reuse what we don't have */
342         else if (obj_type == OBJ_DELTA)
343                 to_reuse = 1;   /* check_object() decided it for us */
344         else if (obj_type != entry->in_pack_type)
345                 to_reuse = 0;   /* pack has delta which is unusable */
346         else if (entry->delta)
347                 to_reuse = 0;   /* we want to pack afresh */
348         else
349                 to_reuse = 1;   /* we have it in-pack undeltified,
350                                  * and we do not need to deltify it.
351                                  */
352
353         if (!entry->in_pack && !entry->delta) {
354                 unsigned char *map;
355                 unsigned long mapsize;
356                 map = map_sha1_file(entry->sha1, &mapsize);
357                 if (map && !legacy_loose_object(map)) {
358                         /* We can copy straight into the pack file */
359                         if (revalidate_loose_object(entry, map, mapsize))
360                                 die("corrupt loose object %s",
361                                     sha1_to_hex(entry->sha1));
362                         sha1write(f, map, mapsize);
363                         munmap(map, mapsize);
364                         written++;
365                         reused++;
366                         return mapsize;
367                 }
368                 if (map)
369                         munmap(map, mapsize);
370         }
371
372         if (!to_reuse) {
373                 buf = read_sha1_file(entry->sha1, type, &size);
374                 if (!buf)
375                         die("unable to read %s", sha1_to_hex(entry->sha1));
376                 if (size != entry->size)
377                         die("object %s size inconsistency (%lu vs %lu)",
378                             sha1_to_hex(entry->sha1), size, entry->size);
379                 if (entry->delta) {
380                         buf = delta_against(buf, size, entry);
381                         size = entry->delta_size;
382                         obj_type = OBJ_DELTA;
383                 }
384                 /*
385                  * The object header is a byte of 'type' followed by zero or
386                  * more bytes of length.  For deltas, the 20 bytes of delta
387                  * sha1 follows that.
388                  */
389                 hdrlen = encode_header(obj_type, size, header);
390                 sha1write(f, header, hdrlen);
391
392                 if (entry->delta) {
393                         sha1write(f, entry->delta, 20);
394                         hdrlen += 20;
395                 }
396                 datalen = sha1write_compressed(f, buf, size);
397                 free(buf);
398         }
399         else {
400                 struct packed_git *p = entry->in_pack;
401                 use_packed_git(p);
402
403                 datalen = find_packed_object_size(p, entry->in_pack_offset);
404                 buf = (char *) p->pack_base + entry->in_pack_offset;
405
406                 if (revalidate_pack_entry(entry, buf, datalen))
407                         die("corrupt delta in pack %s", sha1_to_hex(entry->sha1));
408                 sha1write(f, buf, datalen);
409                 unuse_packed_git(p);
410                 hdrlen = 0; /* not really */
411                 if (obj_type == OBJ_DELTA)
412                         reused_delta++;
413                 reused++;
414         }
415         if (obj_type == OBJ_DELTA)
416                 written_delta++;
417         written++;
418         return hdrlen + datalen;
419 }
420
421 static unsigned long write_one(struct sha1file *f,
422                                struct object_entry *e,
423                                unsigned long offset)
424 {
425         if (e->offset)
426                 /* offset starts from header size and cannot be zero
427                  * if it is written already.
428                  */
429                 return offset;
430         e->offset = offset;
431         offset += write_object(f, e);
432         /* if we are deltified, write out its base object. */
433         if (e->delta)
434                 offset = write_one(f, e->delta, offset);
435         return offset;
436 }
437
438 static void write_pack_file(void)
439 {
440         int i;
441         struct sha1file *f;
442         unsigned long offset;
443         struct pack_header hdr;
444         unsigned last_percent = 999;
445         int do_progress = 0;
446
447         if (!base_name)
448                 f = sha1fd(1, "<stdout>");
449         else {
450                 f = sha1create("%s-%s.%s", base_name,
451                                sha1_to_hex(object_list_sha1), "pack");
452                 do_progress = progress;
453         }
454         if (do_progress)
455                 fprintf(stderr, "Writing %d objects.\n", nr_result);
456
457         hdr.hdr_signature = htonl(PACK_SIGNATURE);
458         hdr.hdr_version = htonl(PACK_VERSION);
459         hdr.hdr_entries = htonl(nr_result);
460         sha1write(f, &hdr, sizeof(hdr));
461         offset = sizeof(hdr);
462         if (!nr_result)
463                 goto done;
464         for (i = 0; i < nr_objects; i++) {
465                 offset = write_one(f, objects + i, offset);
466                 if (do_progress) {
467                         unsigned percent = written * 100 / nr_result;
468                         if (progress_update || percent != last_percent) {
469                                 fprintf(stderr, "%4u%% (%u/%u) done\r",
470                                         percent, written, nr_result);
471                                 progress_update = 0;
472                                 last_percent = percent;
473                         }
474                 }
475         }
476         if (do_progress)
477                 fputc('\n', stderr);
478  done:
479         sha1close(f, pack_file_sha1, 1);
480 }
481
482 static void write_index_file(void)
483 {
484         int i;
485         struct sha1file *f = sha1create("%s-%s.%s", base_name,
486                                         sha1_to_hex(object_list_sha1), "idx");
487         struct object_entry **list = sorted_by_sha;
488         struct object_entry **last = list + nr_result;
489         unsigned int array[256];
490
491         /*
492          * Write the first-level table (the list is sorted,
493          * but we use a 256-entry lookup to be able to avoid
494          * having to do eight extra binary search iterations).
495          */
496         for (i = 0; i < 256; i++) {
497                 struct object_entry **next = list;
498                 while (next < last) {
499                         struct object_entry *entry = *next;
500                         if (entry->sha1[0] != i)
501                                 break;
502                         next++;
503                 }
504                 array[i] = htonl(next - sorted_by_sha);
505                 list = next;
506         }
507         sha1write(f, array, 256 * sizeof(int));
508
509         /*
510          * Write the actual SHA1 entries..
511          */
512         list = sorted_by_sha;
513         for (i = 0; i < nr_result; i++) {
514                 struct object_entry *entry = *list++;
515                 unsigned int offset = htonl(entry->offset);
516                 sha1write(f, &offset, 4);
517                 sha1write(f, entry->sha1, 20);
518         }
519         sha1write(f, pack_file_sha1, 20);
520         sha1close(f, NULL, 1);
521 }
522
523 static int locate_object_entry_hash(const unsigned char *sha1)
524 {
525         int i;
526         unsigned int ui;
527         memcpy(&ui, sha1, sizeof(unsigned int));
528         i = ui % object_ix_hashsz;
529         while (0 < object_ix[i]) {
530                 if (!hashcmp(sha1, objects[object_ix[i] - 1].sha1))
531                         return i;
532                 if (++i == object_ix_hashsz)
533                         i = 0;
534         }
535         return -1 - i;
536 }
537
538 static struct object_entry *locate_object_entry(const unsigned char *sha1)
539 {
540         int i;
541
542         if (!object_ix_hashsz)
543                 return NULL;
544
545         i = locate_object_entry_hash(sha1);
546         if (0 <= i)
547                 return &objects[object_ix[i]-1];
548         return NULL;
549 }
550
551 static void rehash_objects(void)
552 {
553         int i;
554         struct object_entry *oe;
555
556         object_ix_hashsz = nr_objects * 3;
557         if (object_ix_hashsz < 1024)
558                 object_ix_hashsz = 1024;
559         object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
560         memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
561         for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
562                 int ix = locate_object_entry_hash(oe->sha1);
563                 if (0 <= ix)
564                         continue;
565                 ix = -1 - ix;
566                 object_ix[ix] = i + 1;
567         }
568 }
569
570 static unsigned name_hash(const char *name)
571 {
572         unsigned char c;
573         unsigned hash = 0;
574
575         /*
576          * This effectively just creates a sortable number from the
577          * last sixteen non-whitespace characters. Last characters
578          * count "most", so things that end in ".c" sort together.
579          */
580         while ((c = *name++) != 0) {
581                 if (isspace(c))
582                         continue;
583                 hash = (hash >> 2) + (c << 24);
584         }
585         return hash;
586 }
587
588 static int add_object_entry(const unsigned char *sha1, unsigned hash, int exclude)
589 {
590         unsigned int idx = nr_objects;
591         struct object_entry *entry;
592         struct packed_git *p;
593         unsigned int found_offset = 0;
594         struct packed_git *found_pack = NULL;
595         int ix, status = 0;
596
597         if (!exclude) {
598                 for (p = packed_git; p; p = p->next) {
599                         struct pack_entry e;
600                         if (find_pack_entry_one(sha1, &e, p)) {
601                                 if (incremental)
602                                         return 0;
603                                 if (local && !p->pack_local)
604                                         return 0;
605                                 if (!found_pack) {
606                                         found_offset = e.offset;
607                                         found_pack = e.p;
608                                 }
609                         }
610                 }
611         }
612         if ((entry = locate_object_entry(sha1)) != NULL)
613                 goto already_added;
614
615         if (idx >= nr_alloc) {
616                 unsigned int needed = (idx + 1024) * 3 / 2;
617                 objects = xrealloc(objects, needed * sizeof(*entry));
618                 nr_alloc = needed;
619         }
620         entry = objects + idx;
621         nr_objects = idx + 1;
622         memset(entry, 0, sizeof(*entry));
623         hashcpy(entry->sha1, sha1);
624         entry->hash = hash;
625
626         if (object_ix_hashsz * 3 <= nr_objects * 4)
627                 rehash_objects();
628         else {
629                 ix = locate_object_entry_hash(entry->sha1);
630                 if (0 <= ix)
631                         die("internal error in object hashing.");
632                 object_ix[-1 - ix] = idx + 1;
633         }
634         status = 1;
635
636  already_added:
637         if (progress_update) {
638                 fprintf(stderr, "Counting objects...%d\r", nr_objects);
639                 progress_update = 0;
640         }
641         if (exclude)
642                 entry->preferred_base = 1;
643         else {
644                 if (found_pack) {
645                         entry->in_pack = found_pack;
646                         entry->in_pack_offset = found_offset;
647                 }
648         }
649         return status;
650 }
651
652 struct pbase_tree_cache {
653         unsigned char sha1[20];
654         int ref;
655         int temporary;
656         void *tree_data;
657         unsigned long tree_size;
658 };
659
660 static struct pbase_tree_cache *(pbase_tree_cache[256]);
661 static int pbase_tree_cache_ix(const unsigned char *sha1)
662 {
663         return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
664 }
665 static int pbase_tree_cache_ix_incr(int ix)
666 {
667         return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
668 }
669
670 static struct pbase_tree {
671         struct pbase_tree *next;
672         /* This is a phony "cache" entry; we are not
673          * going to evict it nor find it through _get()
674          * mechanism -- this is for the toplevel node that
675          * would almost always change with any commit.
676          */
677         struct pbase_tree_cache pcache;
678 } *pbase_tree;
679
680 static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
681 {
682         struct pbase_tree_cache *ent, *nent;
683         void *data;
684         unsigned long size;
685         char type[20];
686         int neigh;
687         int my_ix = pbase_tree_cache_ix(sha1);
688         int available_ix = -1;
689
690         /* pbase-tree-cache acts as a limited hashtable.
691          * your object will be found at your index or within a few
692          * slots after that slot if it is cached.
693          */
694         for (neigh = 0; neigh < 8; neigh++) {
695                 ent = pbase_tree_cache[my_ix];
696                 if (ent && !hashcmp(ent->sha1, sha1)) {
697                         ent->ref++;
698                         return ent;
699                 }
700                 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
701                          ((0 <= available_ix) &&
702                           (!ent && pbase_tree_cache[available_ix])))
703                         available_ix = my_ix;
704                 if (!ent)
705                         break;
706                 my_ix = pbase_tree_cache_ix_incr(my_ix);
707         }
708
709         /* Did not find one.  Either we got a bogus request or
710          * we need to read and perhaps cache.
711          */
712         data = read_sha1_file(sha1, type, &size);
713         if (!data)
714                 return NULL;
715         if (strcmp(type, tree_type)) {
716                 free(data);
717                 return NULL;
718         }
719
720         /* We need to either cache or return a throwaway copy */
721
722         if (available_ix < 0)
723                 ent = NULL;
724         else {
725                 ent = pbase_tree_cache[available_ix];
726                 my_ix = available_ix;
727         }
728
729         if (!ent) {
730                 nent = xmalloc(sizeof(*nent));
731                 nent->temporary = (available_ix < 0);
732         }
733         else {
734                 /* evict and reuse */
735                 free(ent->tree_data);
736                 nent = ent;
737         }
738         hashcpy(nent->sha1, sha1);
739         nent->tree_data = data;
740         nent->tree_size = size;
741         nent->ref = 1;
742         if (!nent->temporary)
743                 pbase_tree_cache[my_ix] = nent;
744         return nent;
745 }
746
747 static void pbase_tree_put(struct pbase_tree_cache *cache)
748 {
749         if (!cache->temporary) {
750                 cache->ref--;
751                 return;
752         }
753         free(cache->tree_data);
754         free(cache);
755 }
756
757 static int name_cmp_len(const char *name)
758 {
759         int i;
760         for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
761                 ;
762         return i;
763 }
764
765 static void add_pbase_object(struct tree_desc *tree,
766                              const char *name,
767                              int cmplen,
768                              const char *fullname)
769 {
770         struct name_entry entry;
771
772         while (tree_entry(tree,&entry)) {
773                 unsigned long size;
774                 char type[20];
775
776                 if (entry.pathlen != cmplen ||
777                     memcmp(entry.path, name, cmplen) ||
778                     !has_sha1_file(entry.sha1) ||
779                     sha1_object_info(entry.sha1, type, &size))
780                         continue;
781                 if (name[cmplen] != '/') {
782                         unsigned hash = name_hash(fullname);
783                         add_object_entry(entry.sha1, hash, 1);
784                         return;
785                 }
786                 if (!strcmp(type, tree_type)) {
787                         struct tree_desc sub;
788                         struct pbase_tree_cache *tree;
789                         const char *down = name+cmplen+1;
790                         int downlen = name_cmp_len(down);
791
792                         tree = pbase_tree_get(entry.sha1);
793                         if (!tree)
794                                 return;
795                         sub.buf = tree->tree_data;
796                         sub.size = tree->tree_size;
797
798                         add_pbase_object(&sub, down, downlen, fullname);
799                         pbase_tree_put(tree);
800                 }
801         }
802 }
803
804 static unsigned *done_pbase_paths;
805 static int done_pbase_paths_num;
806 static int done_pbase_paths_alloc;
807 static int done_pbase_path_pos(unsigned hash)
808 {
809         int lo = 0;
810         int hi = done_pbase_paths_num;
811         while (lo < hi) {
812                 int mi = (hi + lo) / 2;
813                 if (done_pbase_paths[mi] == hash)
814                         return mi;
815                 if (done_pbase_paths[mi] < hash)
816                         hi = mi;
817                 else
818                         lo = mi + 1;
819         }
820         return -lo-1;
821 }
822
823 static int check_pbase_path(unsigned hash)
824 {
825         int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
826         if (0 <= pos)
827                 return 1;
828         pos = -pos - 1;
829         if (done_pbase_paths_alloc <= done_pbase_paths_num) {
830                 done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
831                 done_pbase_paths = xrealloc(done_pbase_paths,
832                                             done_pbase_paths_alloc *
833                                             sizeof(unsigned));
834         }
835         done_pbase_paths_num++;
836         if (pos < done_pbase_paths_num)
837                 memmove(done_pbase_paths + pos + 1,
838                         done_pbase_paths + pos,
839                         (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
840         done_pbase_paths[pos] = hash;
841         return 0;
842 }
843
844 static void add_preferred_base_object(char *name, unsigned hash)
845 {
846         struct pbase_tree *it;
847         int cmplen = name_cmp_len(name);
848
849         if (check_pbase_path(hash))
850                 return;
851
852         for (it = pbase_tree; it; it = it->next) {
853                 if (cmplen == 0) {
854                         hash = name_hash("");
855                         add_object_entry(it->pcache.sha1, hash, 1);
856                 }
857                 else {
858                         struct tree_desc tree;
859                         tree.buf = it->pcache.tree_data;
860                         tree.size = it->pcache.tree_size;
861                         add_pbase_object(&tree, name, cmplen, name);
862                 }
863         }
864 }
865
866 static void add_preferred_base(unsigned char *sha1)
867 {
868         struct pbase_tree *it;
869         void *data;
870         unsigned long size;
871         unsigned char tree_sha1[20];
872
873         data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
874         if (!data)
875                 return;
876
877         for (it = pbase_tree; it; it = it->next) {
878                 if (!hashcmp(it->pcache.sha1, tree_sha1)) {
879                         free(data);
880                         return;
881                 }
882         }
883
884         it = xcalloc(1, sizeof(*it));
885         it->next = pbase_tree;
886         pbase_tree = it;
887
888         hashcpy(it->pcache.sha1, tree_sha1);
889         it->pcache.tree_data = data;
890         it->pcache.tree_size = size;
891 }
892
893 static void check_object(struct object_entry *entry)
894 {
895         char type[20];
896
897         if (entry->in_pack && !entry->preferred_base) {
898                 unsigned char base[20];
899                 unsigned long size;
900                 struct object_entry *base_entry;
901
902                 /* We want in_pack_type even if we do not reuse delta.
903                  * There is no point not reusing non-delta representations.
904                  */
905                 check_reuse_pack_delta(entry->in_pack,
906                                        entry->in_pack_offset,
907                                        base, &size,
908                                        &entry->in_pack_type);
909
910                 /* Check if it is delta, and the base is also an object
911                  * we are going to pack.  If so we will reuse the existing
912                  * delta.
913                  */
914                 if (!no_reuse_delta &&
915                     entry->in_pack_type == OBJ_DELTA &&
916                     (base_entry = locate_object_entry(base)) &&
917                     (!base_entry->preferred_base)) {
918
919                         /* Depth value does not matter - find_deltas()
920                          * will never consider reused delta as the
921                          * base object to deltify other objects
922                          * against, in order to avoid circular deltas.
923                          */
924
925                         /* uncompressed size of the delta data */
926                         entry->size = entry->delta_size = size;
927                         entry->delta = base_entry;
928                         entry->type = OBJ_DELTA;
929
930                         entry->delta_sibling = base_entry->delta_child;
931                         base_entry->delta_child = entry;
932
933                         return;
934                 }
935                 /* Otherwise we would do the usual */
936         }
937
938         if (sha1_object_info(entry->sha1, type, &entry->size))
939                 die("unable to get type of object %s",
940                     sha1_to_hex(entry->sha1));
941
942         if (!strcmp(type, commit_type)) {
943                 entry->type = OBJ_COMMIT;
944         } else if (!strcmp(type, tree_type)) {
945                 entry->type = OBJ_TREE;
946         } else if (!strcmp(type, blob_type)) {
947                 entry->type = OBJ_BLOB;
948         } else if (!strcmp(type, tag_type)) {
949                 entry->type = OBJ_TAG;
950         } else
951                 die("unable to pack object %s of type %s",
952                     sha1_to_hex(entry->sha1), type);
953 }
954
955 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
956 {
957         struct object_entry *child = me->delta_child;
958         unsigned int m = n;
959         while (child) {
960                 unsigned int c = check_delta_limit(child, n + 1);
961                 if (m < c)
962                         m = c;
963                 child = child->delta_sibling;
964         }
965         return m;
966 }
967
968 static void get_object_details(void)
969 {
970         int i;
971         struct object_entry *entry;
972
973         prepare_pack_ix();
974         for (i = 0, entry = objects; i < nr_objects; i++, entry++)
975                 check_object(entry);
976
977         if (nr_objects == nr_result) {
978                 /*
979                  * Depth of objects that depend on the entry -- this
980                  * is subtracted from depth-max to break too deep
981                  * delta chain because of delta data reusing.
982                  * However, we loosen this restriction when we know we
983                  * are creating a thin pack -- it will have to be
984                  * expanded on the other end anyway, so do not
985                  * artificially cut the delta chain and let it go as
986                  * deep as it wants.
987                  */
988                 for (i = 0, entry = objects; i < nr_objects; i++, entry++)
989                         if (!entry->delta && entry->delta_child)
990                                 entry->delta_limit =
991                                         check_delta_limit(entry, 1);
992         }
993 }
994
995 typedef int (*entry_sort_t)(const struct object_entry *, const struct object_entry *);
996
997 static entry_sort_t current_sort;
998
999 static int sort_comparator(const void *_a, const void *_b)
1000 {
1001         struct object_entry *a = *(struct object_entry **)_a;
1002         struct object_entry *b = *(struct object_entry **)_b;
1003         return current_sort(a,b);
1004 }
1005
1006 static struct object_entry **create_sorted_list(entry_sort_t sort)
1007 {
1008         struct object_entry **list = xmalloc(nr_objects * sizeof(struct object_entry *));
1009         int i;
1010
1011         for (i = 0; i < nr_objects; i++)
1012                 list[i] = objects + i;
1013         current_sort = sort;
1014         qsort(list, nr_objects, sizeof(struct object_entry *), sort_comparator);
1015         return list;
1016 }
1017
1018 static int sha1_sort(const struct object_entry *a, const struct object_entry *b)
1019 {
1020         return hashcmp(a->sha1, b->sha1);
1021 }
1022
1023 static struct object_entry **create_final_object_list(void)
1024 {
1025         struct object_entry **list;
1026         int i, j;
1027
1028         for (i = nr_result = 0; i < nr_objects; i++)
1029                 if (!objects[i].preferred_base)
1030                         nr_result++;
1031         list = xmalloc(nr_result * sizeof(struct object_entry *));
1032         for (i = j = 0; i < nr_objects; i++) {
1033                 if (!objects[i].preferred_base)
1034                         list[j++] = objects + i;
1035         }
1036         current_sort = sha1_sort;
1037         qsort(list, nr_result, sizeof(struct object_entry *), sort_comparator);
1038         return list;
1039 }
1040
1041 static int type_size_sort(const struct object_entry *a, const struct object_entry *b)
1042 {
1043         if (a->type < b->type)
1044                 return -1;
1045         if (a->type > b->type)
1046                 return 1;
1047         if (a->hash < b->hash)
1048                 return -1;
1049         if (a->hash > b->hash)
1050                 return 1;
1051         if (a->preferred_base < b->preferred_base)
1052                 return -1;
1053         if (a->preferred_base > b->preferred_base)
1054                 return 1;
1055         if (a->size < b->size)
1056                 return -1;
1057         if (a->size > b->size)
1058                 return 1;
1059         return a < b ? -1 : (a > b);
1060 }
1061
1062 struct unpacked {
1063         struct object_entry *entry;
1064         void *data;
1065         struct delta_index *index;
1066 };
1067
1068 /*
1069  * We search for deltas _backwards_ in a list sorted by type and
1070  * by size, so that we see progressively smaller and smaller files.
1071  * That's because we prefer deltas to be from the bigger file
1072  * to the smaller - deletes are potentially cheaper, but perhaps
1073  * more importantly, the bigger file is likely the more recent
1074  * one.
1075  */
1076 static int try_delta(struct unpacked *trg, struct unpacked *src,
1077                      unsigned max_depth)
1078 {
1079         struct object_entry *trg_entry = trg->entry;
1080         struct object_entry *src_entry = src->entry;
1081         unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1082         char type[10];
1083         void *delta_buf;
1084
1085         /* Don't bother doing diffs between different types */
1086         if (trg_entry->type != src_entry->type)
1087                 return -1;
1088
1089         /* We do not compute delta to *create* objects we are not
1090          * going to pack.
1091          */
1092         if (trg_entry->preferred_base)
1093                 return -1;
1094
1095         /*
1096          * We do not bother to try a delta that we discarded
1097          * on an earlier try, but only when reusing delta data.
1098          */
1099         if (!no_reuse_delta && trg_entry->in_pack &&
1100             trg_entry->in_pack == src_entry->in_pack)
1101                 return 0;
1102
1103         /*
1104          * If the current object is at pack edge, take the depth the
1105          * objects that depend on the current object into account --
1106          * otherwise they would become too deep.
1107          */
1108         if (trg_entry->delta_child) {
1109                 if (max_depth <= trg_entry->delta_limit)
1110                         return 0;
1111                 max_depth -= trg_entry->delta_limit;
1112         }
1113         if (src_entry->depth >= max_depth)
1114                 return 0;
1115
1116         /* Now some size filtering heuristics. */
1117         trg_size = trg_entry->size;
1118         max_size = trg_size/2 - 20;
1119         max_size = max_size * (max_depth - src_entry->depth) / max_depth;
1120         if (max_size == 0)
1121                 return 0;
1122         if (trg_entry->delta && trg_entry->delta_size <= max_size)
1123                 max_size = trg_entry->delta_size-1;
1124         src_size = src_entry->size;
1125         sizediff = src_size < trg_size ? trg_size - src_size : 0;
1126         if (sizediff >= max_size)
1127                 return 0;
1128
1129         /* Load data if not already done */
1130         if (!trg->data) {
1131                 trg->data = read_sha1_file(trg_entry->sha1, type, &sz);
1132                 if (sz != trg_size)
1133                         die("object %s inconsistent object length (%lu vs %lu)",
1134                             sha1_to_hex(trg_entry->sha1), sz, trg_size);
1135         }
1136         if (!src->data) {
1137                 src->data = read_sha1_file(src_entry->sha1, type, &sz);
1138                 if (sz != src_size)
1139                         die("object %s inconsistent object length (%lu vs %lu)",
1140                             sha1_to_hex(src_entry->sha1), sz, src_size);
1141         }
1142         if (!src->index) {
1143                 src->index = create_delta_index(src->data, src_size);
1144                 if (!src->index)
1145                         die("out of memory");
1146         }
1147
1148         delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1149         if (!delta_buf)
1150                 return 0;
1151
1152         trg_entry->delta = src_entry;
1153         trg_entry->delta_size = delta_size;
1154         trg_entry->depth = src_entry->depth + 1;
1155         free(delta_buf);
1156         return 1;
1157 }
1158
1159 static void progress_interval(int signum)
1160 {
1161         progress_update = 1;
1162 }
1163
1164 static void find_deltas(struct object_entry **list, int window, int depth)
1165 {
1166         int i, idx;
1167         unsigned int array_size = window * sizeof(struct unpacked);
1168         struct unpacked *array = xmalloc(array_size);
1169         unsigned processed = 0;
1170         unsigned last_percent = 999;
1171
1172         memset(array, 0, array_size);
1173         i = nr_objects;
1174         idx = 0;
1175         if (progress)
1176                 fprintf(stderr, "Deltifying %d objects.\n", nr_result);
1177
1178         while (--i >= 0) {
1179                 struct object_entry *entry = list[i];
1180                 struct unpacked *n = array + idx;
1181                 int j;
1182
1183                 if (!entry->preferred_base)
1184                         processed++;
1185
1186                 if (progress) {
1187                         unsigned percent = processed * 100 / nr_result;
1188                         if (percent != last_percent || progress_update) {
1189                                 fprintf(stderr, "%4u%% (%u/%u) done\r",
1190                                         percent, processed, nr_result);
1191                                 progress_update = 0;
1192                                 last_percent = percent;
1193                         }
1194                 }
1195
1196                 if (entry->delta)
1197                         /* This happens if we decided to reuse existing
1198                          * delta from a pack.  "!no_reuse_delta &&" is implied.
1199                          */
1200                         continue;
1201
1202                 if (entry->size < 50)
1203                         continue;
1204                 free_delta_index(n->index);
1205                 n->index = NULL;
1206                 free(n->data);
1207                 n->data = NULL;
1208                 n->entry = entry;
1209
1210                 j = window;
1211                 while (--j > 0) {
1212                         unsigned int other_idx = idx + j;
1213                         struct unpacked *m;
1214                         if (other_idx >= window)
1215                                 other_idx -= window;
1216                         m = array + other_idx;
1217                         if (!m->entry)
1218                                 break;
1219                         if (try_delta(n, m, depth) < 0)
1220                                 break;
1221                 }
1222                 /* if we made n a delta, and if n is already at max
1223                  * depth, leaving it in the window is pointless.  we
1224                  * should evict it first.
1225                  */
1226                 if (entry->delta && depth <= entry->depth)
1227                         continue;
1228
1229                 idx++;
1230                 if (idx >= window)
1231                         idx = 0;
1232         }
1233
1234         if (progress)
1235                 fputc('\n', stderr);
1236
1237         for (i = 0; i < window; ++i) {
1238                 free_delta_index(array[i].index);
1239                 free(array[i].data);
1240         }
1241         free(array);
1242 }
1243
1244 static void prepare_pack(int window, int depth)
1245 {
1246         get_object_details();
1247         sorted_by_type = create_sorted_list(type_size_sort);
1248         if (window && depth)
1249                 find_deltas(sorted_by_type, window+1, depth);
1250 }
1251
1252 static int reuse_cached_pack(unsigned char *sha1)
1253 {
1254         static const char cache[] = "pack-cache/pack-%s.%s";
1255         char *cached_pack, *cached_idx;
1256         int ifd, ofd, ifd_ix = -1;
1257
1258         cached_pack = git_path(cache, sha1_to_hex(sha1), "pack");
1259         ifd = open(cached_pack, O_RDONLY);
1260         if (ifd < 0)
1261                 return 0;
1262
1263         if (!pack_to_stdout) {
1264                 cached_idx = git_path(cache, sha1_to_hex(sha1), "idx");
1265                 ifd_ix = open(cached_idx, O_RDONLY);
1266                 if (ifd_ix < 0) {
1267                         close(ifd);
1268                         return 0;
1269                 }
1270         }
1271
1272         if (progress)
1273                 fprintf(stderr, "Reusing %d objects pack %s\n", nr_objects,
1274                         sha1_to_hex(sha1));
1275
1276         if (pack_to_stdout) {
1277                 if (copy_fd(ifd, 1))
1278                         exit(1);
1279                 close(ifd);
1280         }
1281         else {
1282                 char name[PATH_MAX];
1283                 snprintf(name, sizeof(name),
1284                          "%s-%s.%s", base_name, sha1_to_hex(sha1), "pack");
1285                 ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1286                 if (ofd < 0)
1287                         die("unable to open %s (%s)", name, strerror(errno));
1288                 if (copy_fd(ifd, ofd))
1289                         exit(1);
1290                 close(ifd);
1291
1292                 snprintf(name, sizeof(name),
1293                          "%s-%s.%s", base_name, sha1_to_hex(sha1), "idx");
1294                 ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1295                 if (ofd < 0)
1296                         die("unable to open %s (%s)", name, strerror(errno));
1297                 if (copy_fd(ifd_ix, ofd))
1298                         exit(1);
1299                 close(ifd_ix);
1300                 puts(sha1_to_hex(sha1));
1301         }
1302
1303         return 1;
1304 }
1305
1306 static void setup_progress_signal(void)
1307 {
1308         struct sigaction sa;
1309         struct itimerval v;
1310
1311         memset(&sa, 0, sizeof(sa));
1312         sa.sa_handler = progress_interval;
1313         sigemptyset(&sa.sa_mask);
1314         sa.sa_flags = SA_RESTART;
1315         sigaction(SIGALRM, &sa, NULL);
1316
1317         v.it_interval.tv_sec = 1;
1318         v.it_interval.tv_usec = 0;
1319         v.it_value = v.it_interval;
1320         setitimer(ITIMER_REAL, &v, NULL);
1321 }
1322
1323 static int git_pack_config(const char *k, const char *v)
1324 {
1325         if(!strcmp(k, "pack.window")) {
1326                 window = git_config_int(k, v);
1327                 return 0;
1328         }
1329         return git_default_config(k, v);
1330 }
1331
1332 static void read_object_list_from_stdin(void)
1333 {
1334         int num_preferred_base = 0;
1335         char line[40 + 1 + PATH_MAX + 2];
1336         unsigned char sha1[20];
1337         unsigned hash;
1338
1339         for (;;) {
1340                 if (!fgets(line, sizeof(line), stdin)) {
1341                         if (feof(stdin))
1342                                 break;
1343                         if (!ferror(stdin))
1344                                 die("fgets returned NULL, not EOF, not error!");
1345                         if (errno != EINTR)
1346                                 die("fgets: %s", strerror(errno));
1347                         clearerr(stdin);
1348                         continue;
1349                 }
1350                 if (line[0] == '-') {
1351                         if (get_sha1_hex(line+1, sha1))
1352                                 die("expected edge sha1, got garbage:\n %s",
1353                                     line);
1354                         if (num_preferred_base++ < window)
1355                                 add_preferred_base(sha1);
1356                         continue;
1357                 }
1358                 if (get_sha1_hex(line, sha1))
1359                         die("expected sha1, got garbage:\n %s", line);
1360
1361                 hash = name_hash(line+41);
1362                 add_preferred_base_object(line+41, hash);
1363                 add_object_entry(sha1, hash, 0);
1364         }
1365 }
1366
1367 /* copied from rev-list but needs to do things slightly differently */
1368 static void mark_edge_parents_uninteresting(struct commit *commit)
1369 {
1370         struct commit_list *parents;
1371
1372         for (parents = commit->parents; parents; parents = parents->next) {
1373                 struct commit *parent = parents->item;
1374                 if (!(parent->object.flags & UNINTERESTING))
1375                         continue;
1376                 mark_tree_uninteresting(parent->tree);
1377         }
1378 }
1379
1380 static void mark_edges_uninteresting(struct commit_list *list)
1381 {
1382         for ( ; list; list = list->next) {
1383                 struct commit *commit = list->item;
1384
1385                 if (commit->object.flags & UNINTERESTING) {
1386                         mark_tree_uninteresting(commit->tree);
1387                         continue;
1388                 }
1389                 mark_edge_parents_uninteresting(commit);
1390         }
1391 }
1392
1393 static void show_commit(struct commit *commit)
1394 {
1395         unsigned hash = name_hash("");
1396         add_object_entry(commit->object.sha1, hash, 0);
1397 }
1398
1399 static void show_object(struct object_array_entry *p)
1400 {
1401         unsigned hash = name_hash(p->name);
1402         add_object_entry(p->item->sha1, hash, 0);
1403 }
1404
1405 static void get_object_list(int unpacked, int all)
1406 {
1407         struct rev_info revs;
1408         char line[1000];
1409         const char *av[6];
1410         int ac;
1411         int flags = 0;
1412
1413         av[0] = "pack-objects";
1414         av[1] = "--objects";
1415         ac = 2;
1416         if (unpacked)
1417                 av[ac++] = "--unpacked";
1418         if (all)
1419                 av[ac++] = "--all";
1420         av[ac++] = "--stdin";
1421         av[ac] = NULL;
1422
1423         init_revisions(&revs, NULL);
1424         save_commit_buffer = 0;
1425         track_object_refs = 0;
1426         setup_revisions(ac, av, &revs, NULL);
1427
1428         /* make sure we did not get pathspecs */
1429         if (revs.prune_data)
1430                 die("pathspec given");
1431
1432         while (fgets(line, sizeof(line), stdin) != NULL) {
1433                 int len = strlen(line);
1434                 if (line[len - 1] == '\n')
1435                         line[--len] = 0;
1436                 if (!len)
1437                         break;
1438                 if (*line == '-') {
1439                         if (!strcmp(line, "--not")) {
1440                                 flags ^= UNINTERESTING;
1441                                 continue;
1442                         }
1443                         die("not a rev '%s'", line);
1444                 }
1445                 if (handle_revision_arg(line, &revs, flags, 1))
1446                         die("bad revision '%s'", line);
1447         }
1448
1449         prepare_revision_walk(&revs);
1450         mark_edges_uninteresting(revs.commits);
1451
1452         traverse_commit_list(&revs, show_commit, show_object);
1453 }
1454
1455 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
1456 {
1457         SHA_CTX ctx;
1458         int depth = 10;
1459         struct object_entry **list;
1460         int use_internal_rev_list = 0;
1461         int unpacked = 0;
1462         int all = 0;
1463         int i;
1464
1465         git_config(git_pack_config);
1466
1467         progress = isatty(2);
1468         for (i = 1; i < argc; i++) {
1469                 const char *arg = argv[i];
1470
1471                 if (*arg != '-')
1472                         break;
1473
1474                 if (!strcmp("--non-empty", arg)) {
1475                         non_empty = 1;
1476                         continue;
1477                 }
1478                 if (!strcmp("--local", arg)) {
1479                         local = 1;
1480                         continue;
1481                 }
1482                 if (!strcmp("--progress", arg)) {
1483                         progress = 1;
1484                         continue;
1485                 }
1486                 if (!strcmp("--incremental", arg)) {
1487                         incremental = 1;
1488                         continue;
1489                 }
1490                 if (!strncmp("--window=", arg, 9)) {
1491                         char *end;
1492                         window = strtoul(arg+9, &end, 0);
1493                         if (!arg[9] || *end)
1494                                 usage(pack_usage);
1495                         continue;
1496                 }
1497                 if (!strncmp("--depth=", arg, 8)) {
1498                         char *end;
1499                         depth = strtoul(arg+8, &end, 0);
1500                         if (!arg[8] || *end)
1501                                 usage(pack_usage);
1502                         continue;
1503                 }
1504                 if (!strcmp("--progress", arg)) {
1505                         progress = 1;
1506                         continue;
1507                 }
1508                 if (!strcmp("-q", arg)) {
1509                         progress = 0;
1510                         continue;
1511                 }
1512                 if (!strcmp("--no-reuse-delta", arg)) {
1513                         no_reuse_delta = 1;
1514                         continue;
1515                 }
1516                 if (!strcmp("--stdout", arg)) {
1517                         pack_to_stdout = 1;
1518                         continue;
1519                 }
1520                 if (!strcmp("--revs", arg)) {
1521                         use_internal_rev_list = 1;
1522                         continue;
1523                 }
1524                 if (!strcmp("--unpacked", arg)) {
1525                         unpacked = 1;
1526                         continue;
1527                 }
1528                 if (!strcmp("--all", arg)) {
1529                         all = 1;
1530                         continue;
1531                 }
1532                 usage(pack_usage);
1533         }
1534
1535         /* Traditionally "pack-objects [options] base extra" failed;
1536          * we would however want to take refs parameter that would
1537          * have been given to upstream rev-list ourselves, which means
1538          * we somehow want to say what the base name is.  So the
1539          * syntax would be:
1540          *
1541          * pack-objects [options] base <refs...>
1542          *
1543          * in other words, we would treat the first non-option as the
1544          * base_name and send everything else to the internal revision
1545          * walker.
1546          */
1547
1548         if (!pack_to_stdout)
1549                 base_name = argv[i++];
1550
1551         if (pack_to_stdout != !base_name)
1552                 usage(pack_usage);
1553
1554         /* --unpacked and --all makes sense only with --revs */
1555         if (!use_internal_rev_list && (unpacked || all))
1556                 usage(pack_usage);
1557
1558         prepare_packed_git();
1559
1560         if (progress) {
1561                 fprintf(stderr, "Generating pack...\n");
1562                 setup_progress_signal();
1563         }
1564
1565         if (!use_internal_rev_list)
1566                 read_object_list_from_stdin();
1567         else
1568                 get_object_list(unpacked, all);
1569
1570         if (progress)
1571                 fprintf(stderr, "Done counting %d objects.\n", nr_objects);
1572         sorted_by_sha = create_final_object_list();
1573         if (non_empty && !nr_result)
1574                 return 0;
1575
1576         SHA1_Init(&ctx);
1577         list = sorted_by_sha;
1578         for (i = 0; i < nr_result; i++) {
1579                 struct object_entry *entry = *list++;
1580                 SHA1_Update(&ctx, entry->sha1, 20);
1581         }
1582         SHA1_Final(object_list_sha1, &ctx);
1583         if (progress && (nr_objects != nr_result))
1584                 fprintf(stderr, "Result has %d objects.\n", nr_result);
1585
1586         if (reuse_cached_pack(object_list_sha1))
1587                 ;
1588         else {
1589                 if (nr_result)
1590                         prepare_pack(window, depth);
1591                 if (progress && pack_to_stdout) {
1592                         /* the other end usually displays progress itself */
1593                         struct itimerval v = {{0,},};
1594                         setitimer(ITIMER_REAL, &v, NULL);
1595                         signal(SIGALRM, SIG_IGN );
1596                         progress_update = 0;
1597                 }
1598                 write_pack_file();
1599                 if (!pack_to_stdout) {
1600                         write_index_file();
1601                         puts(sha1_to_hex(object_list_sha1));
1602                 }
1603         }
1604         if (progress)
1605                 fprintf(stderr, "Total %d, written %d (delta %d), reused %d (delta %d)\n",
1606                         nr_result, written, written_delta, reused, reused_delta);
1607         return 0;
1608 }