Code

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