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