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