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