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