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