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