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