3 #include "repository.h"
13 #include "pack-revindex.h"
14 #include "csum-file.h"
15 #include "tree-walk.h"
18 #include "list-objects.h"
19 #include "list-objects-filter.h"
20 #include "list-objects-filter-options.h"
21 #include "pack-objects.h"
24 #include "streaming.h"
25 #include "thread-utils.h"
26 #include "pack-bitmap.h"
27 #include "reachable.h"
28 #include "sha1-array.h"
29 #include "argv-array.h"
32 #include "object-store.h"
34 static const char *pack_usage[] = {
35 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
36 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
41 * Objects we are going to pack are collected in the `to_pack` structure.
42 * It contains an array (dynamically expanded) of the object data, and a map
43 * that can resolve SHA1s to their position in the array.
45 static struct packing_data to_pack;
47 static struct pack_idx_entry **written_list;
48 static uint32_t nr_result, nr_written;
51 static int reuse_delta = 1, reuse_object = 1;
52 static int keep_unreachable, unpack_unreachable, include_tag;
53 static timestamp_t unpack_unreachable_expiration;
54 static int pack_loose_unreachable;
56 static int have_non_local_packs;
57 static int incremental;
58 static int ignore_packed_keep;
59 static int allow_ofs_delta;
60 static struct pack_idx_option pack_idx_opts;
61 static const char *base_name;
62 static int progress = 1;
63 static int window = 10;
64 static unsigned long pack_size_limit;
65 static int depth = 50;
66 static int delta_search_threads;
67 static int pack_to_stdout;
68 static int num_preferred_base;
69 static struct progress *progress_state;
71 static struct packed_git *reuse_packfile;
72 static uint32_t reuse_packfile_objects;
73 static off_t reuse_packfile_offset;
75 static int use_bitmap_index_default = 1;
76 static int use_bitmap_index = -1;
77 static int write_bitmap_index;
78 static uint16_t write_bitmap_options;
80 static int exclude_promisor_objects;
82 static unsigned long delta_cache_size = 0;
83 static unsigned long max_delta_cache_size = 256 * 1024 * 1024;
84 static unsigned long cache_max_small_delta_size = 1000;
86 static unsigned long window_memory_limit = 0;
88 static struct list_objects_filter_options filter_options;
91 MA_ERROR = 0, /* fail if any missing objects are encountered */
92 MA_ALLOW_ANY, /* silently allow ALL missing objects */
93 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
95 static enum missing_action arg_missing_action;
96 static show_object_fn fn_show_object;
101 static uint32_t written, written_delta;
102 static uint32_t reused, reused_delta;
107 static struct commit **indexed_commits;
108 static unsigned int indexed_commits_nr;
109 static unsigned int indexed_commits_alloc;
111 static void index_commit_for_bitmap(struct commit *commit)
113 if (indexed_commits_nr >= indexed_commits_alloc) {
114 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
115 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
118 indexed_commits[indexed_commits_nr++] = commit;
121 static void *get_delta(struct object_entry *entry)
123 unsigned long size, base_size, delta_size;
124 void *buf, *base_buf, *delta_buf;
125 enum object_type type;
127 buf = read_object_file(&entry->idx.oid, &type, &size);
129 die("unable to read %s", oid_to_hex(&entry->idx.oid));
130 base_buf = read_object_file(&entry->delta->idx.oid, &type, &base_size);
132 die("unable to read %s",
133 oid_to_hex(&entry->delta->idx.oid));
134 delta_buf = diff_delta(base_buf, base_size,
135 buf, size, &delta_size, 0);
136 if (!delta_buf || delta_size != entry->delta_size)
137 die("delta size changed");
143 static unsigned long do_compress(void **pptr, unsigned long size)
147 unsigned long maxsize;
149 git_deflate_init(&stream, pack_compression_level);
150 maxsize = git_deflate_bound(&stream, size);
153 out = xmalloc(maxsize);
157 stream.avail_in = size;
158 stream.next_out = out;
159 stream.avail_out = maxsize;
160 while (git_deflate(&stream, Z_FINISH) == Z_OK)
162 git_deflate_end(&stream);
165 return stream.total_out;
168 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
169 const struct object_id *oid)
172 unsigned char ibuf[1024 * 16];
173 unsigned char obuf[1024 * 16];
174 unsigned long olen = 0;
176 git_deflate_init(&stream, pack_compression_level);
181 readlen = read_istream(st, ibuf, sizeof(ibuf));
183 die(_("unable to read %s"), oid_to_hex(oid));
185 stream.next_in = ibuf;
186 stream.avail_in = readlen;
187 while ((stream.avail_in || readlen == 0) &&
188 (zret == Z_OK || zret == Z_BUF_ERROR)) {
189 stream.next_out = obuf;
190 stream.avail_out = sizeof(obuf);
191 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
192 hashwrite(f, obuf, stream.next_out - obuf);
193 olen += stream.next_out - obuf;
196 die(_("deflate error (%d)"), zret);
198 if (zret != Z_STREAM_END)
199 die(_("deflate error (%d)"), zret);
203 git_deflate_end(&stream);
208 * we are going to reuse the existing object data as is. make
209 * sure it is not corrupt.
211 static int check_pack_inflate(struct packed_git *p,
212 struct pack_window **w_curs,
215 unsigned long expect)
218 unsigned char fakebuf[4096], *in;
221 memset(&stream, 0, sizeof(stream));
222 git_inflate_init(&stream);
224 in = use_pack(p, w_curs, offset, &stream.avail_in);
226 stream.next_out = fakebuf;
227 stream.avail_out = sizeof(fakebuf);
228 st = git_inflate(&stream, Z_FINISH);
229 offset += stream.next_in - in;
230 } while (st == Z_OK || st == Z_BUF_ERROR);
231 git_inflate_end(&stream);
232 return (st == Z_STREAM_END &&
233 stream.total_out == expect &&
234 stream.total_in == len) ? 0 : -1;
237 static void copy_pack_data(struct hashfile *f,
238 struct packed_git *p,
239 struct pack_window **w_curs,
247 in = use_pack(p, w_curs, offset, &avail);
249 avail = (unsigned long)len;
250 hashwrite(f, in, avail);
256 /* Return 0 if we will bust the pack-size limit */
257 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
258 unsigned long limit, int usable_delta)
260 unsigned long size, datalen;
261 unsigned char header[MAX_PACK_OBJECT_HEADER],
262 dheader[MAX_PACK_OBJECT_HEADER];
264 enum object_type type;
266 struct git_istream *st = NULL;
269 if (entry->type == OBJ_BLOB &&
270 entry->size > big_file_threshold &&
271 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
274 buf = read_object_file(&entry->idx.oid, &type, &size);
276 die(_("unable to read %s"),
277 oid_to_hex(&entry->idx.oid));
280 * make sure no cached delta data remains from a
281 * previous attempt before a pack split occurred.
283 FREE_AND_NULL(entry->delta_data);
284 entry->z_delta_size = 0;
285 } else if (entry->delta_data) {
286 size = entry->delta_size;
287 buf = entry->delta_data;
288 entry->delta_data = NULL;
289 type = (allow_ofs_delta && entry->delta->idx.offset) ?
290 OBJ_OFS_DELTA : OBJ_REF_DELTA;
292 buf = get_delta(entry);
293 size = entry->delta_size;
294 type = (allow_ofs_delta && entry->delta->idx.offset) ?
295 OBJ_OFS_DELTA : OBJ_REF_DELTA;
298 if (st) /* large blob case, just assume we don't compress well */
300 else if (entry->z_delta_size)
301 datalen = entry->z_delta_size;
303 datalen = do_compress(&buf, size);
306 * The object header is a byte of 'type' followed by zero or
307 * more bytes of length.
309 hdrlen = encode_in_pack_object_header(header, sizeof(header),
312 if (type == OBJ_OFS_DELTA) {
314 * Deltas with relative base contain an additional
315 * encoding of the relative offset for the delta
316 * base from this object's position in the pack.
318 off_t ofs = entry->idx.offset - entry->delta->idx.offset;
319 unsigned pos = sizeof(dheader) - 1;
320 dheader[pos] = ofs & 127;
322 dheader[--pos] = 128 | (--ofs & 127);
323 if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
329 hashwrite(f, header, hdrlen);
330 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
331 hdrlen += sizeof(dheader) - pos;
332 } else if (type == OBJ_REF_DELTA) {
334 * Deltas with a base reference contain
335 * an additional 20 bytes for the base sha1.
337 if (limit && hdrlen + 20 + datalen + 20 >= limit) {
343 hashwrite(f, header, hdrlen);
344 hashwrite(f, entry->delta->idx.oid.hash, 20);
347 if (limit && hdrlen + datalen + 20 >= limit) {
353 hashwrite(f, header, hdrlen);
356 datalen = write_large_blob_data(st, f, &entry->idx.oid);
359 hashwrite(f, buf, datalen);
363 return hdrlen + datalen;
366 /* Return 0 if we will bust the pack-size limit */
367 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
368 unsigned long limit, int usable_delta)
370 struct packed_git *p = entry->in_pack;
371 struct pack_window *w_curs = NULL;
372 struct revindex_entry *revidx;
374 enum object_type type = entry->type;
376 unsigned char header[MAX_PACK_OBJECT_HEADER],
377 dheader[MAX_PACK_OBJECT_HEADER];
381 type = (allow_ofs_delta && entry->delta->idx.offset) ?
382 OBJ_OFS_DELTA : OBJ_REF_DELTA;
383 hdrlen = encode_in_pack_object_header(header, sizeof(header),
386 offset = entry->in_pack_offset;
387 revidx = find_pack_revindex(p, offset);
388 datalen = revidx[1].offset - offset;
389 if (!pack_to_stdout && p->index_version > 1 &&
390 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
391 error("bad packed object CRC for %s",
392 oid_to_hex(&entry->idx.oid));
394 return write_no_reuse_object(f, entry, limit, usable_delta);
397 offset += entry->in_pack_header_size;
398 datalen -= entry->in_pack_header_size;
400 if (!pack_to_stdout && p->index_version == 1 &&
401 check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) {
402 error("corrupt packed object for %s",
403 oid_to_hex(&entry->idx.oid));
405 return write_no_reuse_object(f, entry, limit, usable_delta);
408 if (type == OBJ_OFS_DELTA) {
409 off_t ofs = entry->idx.offset - entry->delta->idx.offset;
410 unsigned pos = sizeof(dheader) - 1;
411 dheader[pos] = ofs & 127;
413 dheader[--pos] = 128 | (--ofs & 127);
414 if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
418 hashwrite(f, header, hdrlen);
419 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
420 hdrlen += sizeof(dheader) - pos;
422 } else if (type == OBJ_REF_DELTA) {
423 if (limit && hdrlen + 20 + datalen + 20 >= limit) {
427 hashwrite(f, header, hdrlen);
428 hashwrite(f, entry->delta->idx.oid.hash, 20);
432 if (limit && hdrlen + datalen + 20 >= limit) {
436 hashwrite(f, header, hdrlen);
438 copy_pack_data(f, p, &w_curs, offset, datalen);
441 return hdrlen + datalen;
444 /* Return 0 if we will bust the pack-size limit */
445 static off_t write_object(struct hashfile *f,
446 struct object_entry *entry,
451 int usable_delta, to_reuse;
456 /* apply size limit if limited packsize and not first object */
457 if (!pack_size_limit || !nr_written)
459 else if (pack_size_limit <= write_offset)
461 * the earlier object did not fit the limit; avoid
462 * mistaking this with unlimited (i.e. limit = 0).
466 limit = pack_size_limit - write_offset;
469 usable_delta = 0; /* no delta */
470 else if (!pack_size_limit)
471 usable_delta = 1; /* unlimited packfile */
472 else if (entry->delta->idx.offset == (off_t)-1)
473 usable_delta = 0; /* base was written to another pack */
474 else if (entry->delta->idx.offset)
475 usable_delta = 1; /* base already exists in this pack */
477 usable_delta = 0; /* base could end up in another pack */
480 to_reuse = 0; /* explicit */
481 else if (!entry->in_pack)
482 to_reuse = 0; /* can't reuse what we don't have */
483 else if (entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA)
484 /* check_object() decided it for us ... */
485 to_reuse = usable_delta;
486 /* ... but pack split may override that */
487 else if (entry->type != entry->in_pack_type)
488 to_reuse = 0; /* pack has delta which is unusable */
489 else if (entry->delta)
490 to_reuse = 0; /* we want to pack afresh */
492 to_reuse = 1; /* we have it in-pack undeltified,
493 * and we do not need to deltify it.
497 len = write_no_reuse_object(f, entry, limit, usable_delta);
499 len = write_reuse_object(f, entry, limit, usable_delta);
507 entry->idx.crc32 = crc32_end(f);
511 enum write_one_status {
512 WRITE_ONE_SKIP = -1, /* already written */
513 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
514 WRITE_ONE_WRITTEN = 1, /* normal */
515 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
518 static enum write_one_status write_one(struct hashfile *f,
519 struct object_entry *e,
526 * we set offset to 1 (which is an impossible value) to mark
527 * the fact that this object is involved in "write its base
528 * first before writing a deltified object" recursion.
530 recursing = (e->idx.offset == 1);
532 warning("recursive delta detected for object %s",
533 oid_to_hex(&e->idx.oid));
534 return WRITE_ONE_RECURSIVE;
535 } else if (e->idx.offset || e->preferred_base) {
536 /* offset is non zero if object is written already. */
537 return WRITE_ONE_SKIP;
540 /* if we are deltified, write out base object first. */
542 e->idx.offset = 1; /* now recurse */
543 switch (write_one(f, e->delta, offset)) {
544 case WRITE_ONE_RECURSIVE:
545 /* we cannot depend on this one */
550 case WRITE_ONE_BREAK:
551 e->idx.offset = recursing;
552 return WRITE_ONE_BREAK;
556 e->idx.offset = *offset;
557 size = write_object(f, e, *offset);
559 e->idx.offset = recursing;
560 return WRITE_ONE_BREAK;
562 written_list[nr_written++] = &e->idx;
564 /* make sure off_t is sufficiently large not to wrap */
565 if (signed_add_overflows(*offset, size))
566 die("pack too large for current definition of off_t");
568 return WRITE_ONE_WRITTEN;
571 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
574 struct object_id peeled;
575 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
579 if (!peel_ref(path, &peeled)) {
580 entry = packlist_find(&to_pack, peeled.hash, NULL);
587 static inline void add_to_write_order(struct object_entry **wo,
589 struct object_entry *e)
597 static void add_descendants_to_write_order(struct object_entry **wo,
599 struct object_entry *e)
601 int add_to_order = 1;
604 struct object_entry *s;
605 /* add this node... */
606 add_to_write_order(wo, endp, e);
607 /* all its siblings... */
608 for (s = e->delta_sibling; s; s = s->delta_sibling) {
609 add_to_write_order(wo, endp, s);
612 /* drop down a level to add left subtree nodes if possible */
613 if (e->delta_child) {
618 /* our sibling might have some children, it is next */
619 if (e->delta_sibling) {
620 e = e->delta_sibling;
623 /* go back to our parent node */
625 while (e && !e->delta_sibling) {
626 /* we're on the right side of a subtree, keep
627 * going up until we can go right again */
631 /* done- we hit our original root node */
634 /* pass it off to sibling at this level */
635 e = e->delta_sibling;
640 static void add_family_to_write_order(struct object_entry **wo,
642 struct object_entry *e)
644 struct object_entry *root;
646 for (root = e; root->delta; root = root->delta)
648 add_descendants_to_write_order(wo, endp, root);
651 static struct object_entry **compute_write_order(void)
653 unsigned int i, wo_end, last_untagged;
655 struct object_entry **wo;
656 struct object_entry *objects = to_pack.objects;
658 for (i = 0; i < to_pack.nr_objects; i++) {
659 objects[i].tagged = 0;
660 objects[i].filled = 0;
661 objects[i].delta_child = NULL;
662 objects[i].delta_sibling = NULL;
666 * Fully connect delta_child/delta_sibling network.
667 * Make sure delta_sibling is sorted in the original
670 for (i = to_pack.nr_objects; i > 0;) {
671 struct object_entry *e = &objects[--i];
674 /* Mark me as the first child */
675 e->delta_sibling = e->delta->delta_child;
676 e->delta->delta_child = e;
680 * Mark objects that are at the tip of tags.
682 for_each_tag_ref(mark_tagged, NULL);
685 * Give the objects in the original recency order until
686 * we see a tagged tip.
688 ALLOC_ARRAY(wo, to_pack.nr_objects);
689 for (i = wo_end = 0; i < to_pack.nr_objects; i++) {
690 if (objects[i].tagged)
692 add_to_write_order(wo, &wo_end, &objects[i]);
697 * Then fill all the tagged tips.
699 for (; i < to_pack.nr_objects; i++) {
700 if (objects[i].tagged)
701 add_to_write_order(wo, &wo_end, &objects[i]);
705 * And then all remaining commits and tags.
707 for (i = last_untagged; i < to_pack.nr_objects; i++) {
708 if (objects[i].type != OBJ_COMMIT &&
709 objects[i].type != OBJ_TAG)
711 add_to_write_order(wo, &wo_end, &objects[i]);
715 * And then all the trees.
717 for (i = last_untagged; i < to_pack.nr_objects; i++) {
718 if (objects[i].type != OBJ_TREE)
720 add_to_write_order(wo, &wo_end, &objects[i]);
724 * Finally all the rest in really tight order
726 for (i = last_untagged; i < to_pack.nr_objects; i++) {
727 if (!objects[i].filled)
728 add_family_to_write_order(wo, &wo_end, &objects[i]);
731 if (wo_end != to_pack.nr_objects)
732 die("ordered %u objects, expected %"PRIu32, wo_end, to_pack.nr_objects);
737 static off_t write_reused_pack(struct hashfile *f)
739 unsigned char buffer[8192];
740 off_t to_write, total;
743 if (!is_pack_valid(reuse_packfile))
744 die("packfile is invalid: %s", reuse_packfile->pack_name);
746 fd = git_open(reuse_packfile->pack_name);
748 die_errno("unable to open packfile for reuse: %s",
749 reuse_packfile->pack_name);
751 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
752 die_errno("unable to seek in reused packfile");
754 if (reuse_packfile_offset < 0)
755 reuse_packfile_offset = reuse_packfile->pack_size - 20;
757 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
760 int read_pack = xread(fd, buffer, sizeof(buffer));
763 die_errno("unable to read from reused packfile");
765 if (read_pack > to_write)
766 read_pack = to_write;
768 hashwrite(f, buffer, read_pack);
769 to_write -= read_pack;
772 * We don't know the actual number of objects written,
773 * only how many bytes written, how many bytes total, and
774 * how many objects total. So we can fake it by pretending all
775 * objects we are writing are the same size. This gives us a
776 * smooth progress meter, and at the end it matches the true
779 written = reuse_packfile_objects *
780 (((double)(total - to_write)) / total);
781 display_progress(progress_state, written);
785 written = reuse_packfile_objects;
786 display_progress(progress_state, written);
787 return reuse_packfile_offset - sizeof(struct pack_header);
790 static const char no_split_warning[] = N_(
791 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
794 static void write_pack_file(void)
799 uint32_t nr_remaining = nr_result;
800 time_t last_mtime = 0;
801 struct object_entry **write_order;
803 if (progress > pack_to_stdout)
804 progress_state = start_progress(_("Writing objects"), nr_result);
805 ALLOC_ARRAY(written_list, to_pack.nr_objects);
806 write_order = compute_write_order();
809 struct object_id oid;
810 char *pack_tmp_name = NULL;
813 f = hashfd_throughput(1, "<stdout>", progress_state);
815 f = create_tmp_packfile(&pack_tmp_name);
817 offset = write_pack_header(f, nr_remaining);
819 if (reuse_packfile) {
821 assert(pack_to_stdout);
823 packfile_size = write_reused_pack(f);
824 offset += packfile_size;
828 for (; i < to_pack.nr_objects; i++) {
829 struct object_entry *e = write_order[i];
830 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
832 display_progress(progress_state, written);
836 * Did we write the wrong # entries in the header?
837 * If so, rewrite it like in fast-import
839 if (pack_to_stdout) {
840 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
841 } else if (nr_written == nr_remaining) {
842 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
844 int fd = finalize_hashfile(f, oid.hash, 0);
845 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
846 nr_written, oid.hash, offset);
848 if (write_bitmap_index) {
849 warning(_(no_split_warning));
850 write_bitmap_index = 0;
854 if (!pack_to_stdout) {
856 struct strbuf tmpname = STRBUF_INIT;
859 * Packs are runtime accessed in their mtime
860 * order since newer packs are more likely to contain
861 * younger objects. So if we are creating multiple
862 * packs then we should modify the mtime of later ones
863 * to preserve this property.
865 if (stat(pack_tmp_name, &st) < 0) {
866 warning_errno("failed to stat %s", pack_tmp_name);
867 } else if (!last_mtime) {
868 last_mtime = st.st_mtime;
871 utb.actime = st.st_atime;
872 utb.modtime = --last_mtime;
873 if (utime(pack_tmp_name, &utb) < 0)
874 warning_errno("failed utime() on %s", pack_tmp_name);
877 strbuf_addf(&tmpname, "%s-", base_name);
879 if (write_bitmap_index) {
880 bitmap_writer_set_checksum(oid.hash);
881 bitmap_writer_build_type_index(written_list, nr_written);
884 finish_tmp_packfile(&tmpname, pack_tmp_name,
885 written_list, nr_written,
886 &pack_idx_opts, oid.hash);
888 if (write_bitmap_index) {
889 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
891 stop_progress(&progress_state);
893 bitmap_writer_show_progress(progress);
894 bitmap_writer_reuse_bitmaps(&to_pack);
895 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
896 bitmap_writer_build(&to_pack);
897 bitmap_writer_finish(written_list, nr_written,
898 tmpname.buf, write_bitmap_options);
899 write_bitmap_index = 0;
902 strbuf_release(&tmpname);
904 puts(oid_to_hex(&oid));
907 /* mark written objects as written to previous pack */
908 for (j = 0; j < nr_written; j++) {
909 written_list[j]->offset = (off_t)-1;
911 nr_remaining -= nr_written;
912 } while (nr_remaining && i < to_pack.nr_objects);
916 stop_progress(&progress_state);
917 if (written != nr_result)
918 die("wrote %"PRIu32" objects while expecting %"PRIu32,
922 static int no_try_delta(const char *path)
924 static struct attr_check *check;
927 check = attr_check_initl("delta", NULL);
928 if (git_check_attr(path, check))
930 if (ATTR_FALSE(check->items[0].value))
936 * When adding an object, check whether we have already added it
937 * to our packing list. If so, we can skip. However, if we are
938 * being asked to excludei t, but the previous mention was to include
939 * it, make sure to adjust its flags and tweak our numbers accordingly.
941 * As an optimization, we pass out the index position where we would have
942 * found the item, since that saves us from having to look it up again a
943 * few lines later when we want to add the new entry.
945 static int have_duplicate_entry(const struct object_id *oid,
949 struct object_entry *entry;
951 entry = packlist_find(&to_pack, oid->hash, index_pos);
956 if (!entry->preferred_base)
958 entry->preferred_base = 1;
964 static int want_found_object(int exclude, struct packed_git *p)
972 * When asked to do --local (do not include an object that appears in a
973 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
974 * an object that appears in a pack marked with .keep), finding a pack
975 * that matches the criteria is sufficient for us to decide to omit it.
976 * However, even if this pack does not satisfy the criteria, we need to
977 * make sure no copy of this object appears in _any_ pack that makes us
978 * to omit the object, so we need to check all the packs.
980 * We can however first check whether these options can possible matter;
981 * if they do not matter we know we want the object in generated pack.
982 * Otherwise, we signal "-1" at the end to tell the caller that we do
983 * not know either way, and it needs to check more packs.
985 if (!ignore_packed_keep &&
986 (!local || !have_non_local_packs))
989 if (local && !p->pack_local)
991 if (ignore_packed_keep && p->pack_local && p->pack_keep)
994 /* we don't know yet; keep looking for more packs */
999 * Check whether we want the object in the pack (e.g., we do not want
1000 * objects found in non-local stores if the "--local" option was used).
1002 * If the caller already knows an existing pack it wants to take the object
1003 * from, that is passed in *found_pack and *found_offset; otherwise this
1004 * function finds if there is any pack that has the object and returns the pack
1005 * and its offset in these variables.
1007 static int want_object_in_pack(const struct object_id *oid,
1009 struct packed_git **found_pack,
1010 off_t *found_offset)
1013 struct list_head *pos;
1015 if (!exclude && local && has_loose_object_nonlocal(oid->hash))
1019 * If we already know the pack object lives in, start checks from that
1020 * pack - in the usual case when neither --local was given nor .keep files
1021 * are present we will determine the answer right now.
1024 want = want_found_object(exclude, *found_pack);
1028 list_for_each(pos, get_packed_git_mru(the_repository)) {
1029 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1032 if (p == *found_pack)
1033 offset = *found_offset;
1035 offset = find_pack_entry_one(oid->hash, p);
1039 if (!is_pack_valid(p))
1041 *found_offset = offset;
1044 want = want_found_object(exclude, p);
1045 if (!exclude && want > 0)
1047 get_packed_git_mru(the_repository));
1056 static void create_object_entry(const struct object_id *oid,
1057 enum object_type type,
1062 struct packed_git *found_pack,
1065 struct object_entry *entry;
1067 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1072 entry->preferred_base = 1;
1076 entry->in_pack = found_pack;
1077 entry->in_pack_offset = found_offset;
1080 entry->no_try_delta = no_try_delta;
1083 static const char no_closure_warning[] = N_(
1084 "disabling bitmap writing, as some objects are not being packed"
1087 static int add_object_entry(const struct object_id *oid, enum object_type type,
1088 const char *name, int exclude)
1090 struct packed_git *found_pack = NULL;
1091 off_t found_offset = 0;
1094 if (have_duplicate_entry(oid, exclude, &index_pos))
1097 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1098 /* The pack is missing an object, so it will not have closure */
1099 if (write_bitmap_index) {
1100 warning(_(no_closure_warning));
1101 write_bitmap_index = 0;
1106 create_object_entry(oid, type, pack_name_hash(name),
1107 exclude, name && no_try_delta(name),
1108 index_pos, found_pack, found_offset);
1110 display_progress(progress_state, nr_result);
1114 static int add_object_entry_from_bitmap(const struct object_id *oid,
1115 enum object_type type,
1116 int flags, uint32_t name_hash,
1117 struct packed_git *pack, off_t offset)
1121 if (have_duplicate_entry(oid, 0, &index_pos))
1124 if (!want_object_in_pack(oid, 0, &pack, &offset))
1127 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1129 display_progress(progress_state, nr_result);
1133 struct pbase_tree_cache {
1134 struct object_id oid;
1138 unsigned long tree_size;
1141 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1142 static int pbase_tree_cache_ix(const struct object_id *oid)
1144 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1146 static int pbase_tree_cache_ix_incr(int ix)
1148 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1151 static struct pbase_tree {
1152 struct pbase_tree *next;
1153 /* This is a phony "cache" entry; we are not
1154 * going to evict it or find it through _get()
1155 * mechanism -- this is for the toplevel node that
1156 * would almost always change with any commit.
1158 struct pbase_tree_cache pcache;
1161 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1163 struct pbase_tree_cache *ent, *nent;
1166 enum object_type type;
1168 int my_ix = pbase_tree_cache_ix(oid);
1169 int available_ix = -1;
1171 /* pbase-tree-cache acts as a limited hashtable.
1172 * your object will be found at your index or within a few
1173 * slots after that slot if it is cached.
1175 for (neigh = 0; neigh < 8; neigh++) {
1176 ent = pbase_tree_cache[my_ix];
1177 if (ent && !oidcmp(&ent->oid, oid)) {
1181 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1182 ((0 <= available_ix) &&
1183 (!ent && pbase_tree_cache[available_ix])))
1184 available_ix = my_ix;
1187 my_ix = pbase_tree_cache_ix_incr(my_ix);
1190 /* Did not find one. Either we got a bogus request or
1191 * we need to read and perhaps cache.
1193 data = read_object_file(oid, &type, &size);
1196 if (type != OBJ_TREE) {
1201 /* We need to either cache or return a throwaway copy */
1203 if (available_ix < 0)
1206 ent = pbase_tree_cache[available_ix];
1207 my_ix = available_ix;
1211 nent = xmalloc(sizeof(*nent));
1212 nent->temporary = (available_ix < 0);
1215 /* evict and reuse */
1216 free(ent->tree_data);
1219 oidcpy(&nent->oid, oid);
1220 nent->tree_data = data;
1221 nent->tree_size = size;
1223 if (!nent->temporary)
1224 pbase_tree_cache[my_ix] = nent;
1228 static void pbase_tree_put(struct pbase_tree_cache *cache)
1230 if (!cache->temporary) {
1234 free(cache->tree_data);
1238 static int name_cmp_len(const char *name)
1241 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1246 static void add_pbase_object(struct tree_desc *tree,
1249 const char *fullname)
1251 struct name_entry entry;
1254 while (tree_entry(tree,&entry)) {
1255 if (S_ISGITLINK(entry.mode))
1257 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1258 memcmp(name, entry.path, cmplen);
1263 if (name[cmplen] != '/') {
1264 add_object_entry(entry.oid,
1265 object_type(entry.mode),
1269 if (S_ISDIR(entry.mode)) {
1270 struct tree_desc sub;
1271 struct pbase_tree_cache *tree;
1272 const char *down = name+cmplen+1;
1273 int downlen = name_cmp_len(down);
1275 tree = pbase_tree_get(entry.oid);
1278 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1280 add_pbase_object(&sub, down, downlen, fullname);
1281 pbase_tree_put(tree);
1286 static unsigned *done_pbase_paths;
1287 static int done_pbase_paths_num;
1288 static int done_pbase_paths_alloc;
1289 static int done_pbase_path_pos(unsigned hash)
1292 int hi = done_pbase_paths_num;
1294 int mi = lo + (hi - lo) / 2;
1295 if (done_pbase_paths[mi] == hash)
1297 if (done_pbase_paths[mi] < hash)
1305 static int check_pbase_path(unsigned hash)
1307 int pos = done_pbase_path_pos(hash);
1311 ALLOC_GROW(done_pbase_paths,
1312 done_pbase_paths_num + 1,
1313 done_pbase_paths_alloc);
1314 done_pbase_paths_num++;
1315 if (pos < done_pbase_paths_num)
1316 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1317 done_pbase_paths_num - pos - 1);
1318 done_pbase_paths[pos] = hash;
1322 static void add_preferred_base_object(const char *name)
1324 struct pbase_tree *it;
1326 unsigned hash = pack_name_hash(name);
1328 if (!num_preferred_base || check_pbase_path(hash))
1331 cmplen = name_cmp_len(name);
1332 for (it = pbase_tree; it; it = it->next) {
1334 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1337 struct tree_desc tree;
1338 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1339 add_pbase_object(&tree, name, cmplen, name);
1344 static void add_preferred_base(struct object_id *oid)
1346 struct pbase_tree *it;
1349 struct object_id tree_oid;
1351 if (window <= num_preferred_base++)
1354 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1358 for (it = pbase_tree; it; it = it->next) {
1359 if (!oidcmp(&it->pcache.oid, &tree_oid)) {
1365 it = xcalloc(1, sizeof(*it));
1366 it->next = pbase_tree;
1369 oidcpy(&it->pcache.oid, &tree_oid);
1370 it->pcache.tree_data = data;
1371 it->pcache.tree_size = size;
1374 static void cleanup_preferred_base(void)
1376 struct pbase_tree *it;
1382 struct pbase_tree *tmp = it;
1384 free(tmp->pcache.tree_data);
1388 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1389 if (!pbase_tree_cache[i])
1391 free(pbase_tree_cache[i]->tree_data);
1392 FREE_AND_NULL(pbase_tree_cache[i]);
1395 FREE_AND_NULL(done_pbase_paths);
1396 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1399 static void check_object(struct object_entry *entry)
1401 if (entry->in_pack) {
1402 struct packed_git *p = entry->in_pack;
1403 struct pack_window *w_curs = NULL;
1404 const unsigned char *base_ref = NULL;
1405 struct object_entry *base_entry;
1406 unsigned long used, used_0;
1407 unsigned long avail;
1409 unsigned char *buf, c;
1411 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1414 * We want in_pack_type even if we do not reuse delta
1415 * since non-delta representations could still be reused.
1417 used = unpack_object_header_buffer(buf, avail,
1418 &entry->in_pack_type,
1424 * Determine if this is a delta and if so whether we can
1425 * reuse it or not. Otherwise let's find out as cheaply as
1426 * possible what the actual type and size for this object is.
1428 switch (entry->in_pack_type) {
1430 /* Not a delta hence we've already got all we need. */
1431 entry->type = entry->in_pack_type;
1432 entry->in_pack_header_size = used;
1433 if (entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)
1435 unuse_pack(&w_curs);
1438 if (reuse_delta && !entry->preferred_base)
1439 base_ref = use_pack(p, &w_curs,
1440 entry->in_pack_offset + used, NULL);
1441 entry->in_pack_header_size = used + 20;
1444 buf = use_pack(p, &w_curs,
1445 entry->in_pack_offset + used, NULL);
1451 if (!ofs || MSB(ofs, 7)) {
1452 error("delta base offset overflow in pack for %s",
1453 oid_to_hex(&entry->idx.oid));
1457 ofs = (ofs << 7) + (c & 127);
1459 ofs = entry->in_pack_offset - ofs;
1460 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1461 error("delta base offset out of bound for %s",
1462 oid_to_hex(&entry->idx.oid));
1465 if (reuse_delta && !entry->preferred_base) {
1466 struct revindex_entry *revidx;
1467 revidx = find_pack_revindex(p, ofs);
1470 base_ref = nth_packed_object_sha1(p, revidx->nr);
1472 entry->in_pack_header_size = used + used_0;
1476 if (base_ref && (base_entry = packlist_find(&to_pack, base_ref, NULL))) {
1478 * If base_ref was set above that means we wish to
1479 * reuse delta data, and we even found that base
1480 * in the list of objects we want to pack. Goodie!
1482 * Depth value does not matter - find_deltas() will
1483 * never consider reused delta as the base object to
1484 * deltify other objects against, in order to avoid
1487 entry->type = entry->in_pack_type;
1488 entry->delta = base_entry;
1489 entry->delta_size = entry->size;
1490 entry->delta_sibling = base_entry->delta_child;
1491 base_entry->delta_child = entry;
1492 unuse_pack(&w_curs);
1498 * This must be a delta and we already know what the
1499 * final object type is. Let's extract the actual
1500 * object size from the delta header.
1502 entry->size = get_size_from_delta(p, &w_curs,
1503 entry->in_pack_offset + entry->in_pack_header_size);
1504 if (entry->size == 0)
1506 unuse_pack(&w_curs);
1511 * No choice but to fall back to the recursive delta walk
1512 * with sha1_object_info() to find about the object type
1516 unuse_pack(&w_curs);
1519 entry->type = oid_object_info(&entry->idx.oid, &entry->size);
1521 * The error condition is checked in prepare_pack(). This is
1522 * to permit a missing preferred base object to be ignored
1523 * as a preferred base. Doing so can result in a larger
1524 * pack file, but the transfer will still take place.
1528 static int pack_offset_sort(const void *_a, const void *_b)
1530 const struct object_entry *a = *(struct object_entry **)_a;
1531 const struct object_entry *b = *(struct object_entry **)_b;
1533 /* avoid filesystem trashing with loose objects */
1534 if (!a->in_pack && !b->in_pack)
1535 return oidcmp(&a->idx.oid, &b->idx.oid);
1537 if (a->in_pack < b->in_pack)
1539 if (a->in_pack > b->in_pack)
1541 return a->in_pack_offset < b->in_pack_offset ? -1 :
1542 (a->in_pack_offset > b->in_pack_offset);
1546 * Drop an on-disk delta we were planning to reuse. Naively, this would
1547 * just involve blanking out the "delta" field, but we have to deal
1548 * with some extra book-keeping:
1550 * 1. Removing ourselves from the delta_sibling linked list.
1552 * 2. Updating our size/type to the non-delta representation. These were
1553 * either not recorded initially (size) or overwritten with the delta type
1554 * (type) when check_object() decided to reuse the delta.
1556 * 3. Resetting our delta depth, as we are now a base object.
1558 static void drop_reused_delta(struct object_entry *entry)
1560 struct object_entry **p = &entry->delta->delta_child;
1561 struct object_info oi = OBJECT_INFO_INIT;
1565 *p = (*p)->delta_sibling;
1567 p = &(*p)->delta_sibling;
1569 entry->delta = NULL;
1572 oi.sizep = &entry->size;
1573 oi.typep = &entry->type;
1574 if (packed_object_info(entry->in_pack, entry->in_pack_offset, &oi) < 0) {
1576 * We failed to get the info from this pack for some reason;
1577 * fall back to sha1_object_info, which may find another copy.
1578 * And if that fails, the error will be recorded in entry->type
1579 * and dealt with in prepare_pack().
1581 entry->type = oid_object_info(&entry->idx.oid, &entry->size);
1586 * Follow the chain of deltas from this entry onward, throwing away any links
1587 * that cause us to hit a cycle (as determined by the DFS state flags in
1590 * We also detect too-long reused chains that would violate our --depth
1593 static void break_delta_chains(struct object_entry *entry)
1596 * The actual depth of each object we will write is stored as an int,
1597 * as it cannot exceed our int "depth" limit. But before we break
1598 * changes based no that limit, we may potentially go as deep as the
1599 * number of objects, which is elsewhere bounded to a uint32_t.
1601 uint32_t total_depth;
1602 struct object_entry *cur, *next;
1604 for (cur = entry, total_depth = 0;
1606 cur = cur->delta, total_depth++) {
1607 if (cur->dfs_state == DFS_DONE) {
1609 * We've already seen this object and know it isn't
1610 * part of a cycle. We do need to append its depth
1613 total_depth += cur->depth;
1618 * We break cycles before looping, so an ACTIVE state (or any
1619 * other cruft which made its way into the state variable)
1622 if (cur->dfs_state != DFS_NONE)
1623 die("BUG: confusing delta dfs state in first pass: %d",
1627 * Now we know this is the first time we've seen the object. If
1628 * it's not a delta, we're done traversing, but we'll mark it
1629 * done to save time on future traversals.
1632 cur->dfs_state = DFS_DONE;
1637 * Mark ourselves as active and see if the next step causes
1638 * us to cycle to another active object. It's important to do
1639 * this _before_ we loop, because it impacts where we make the
1640 * cut, and thus how our total_depth counter works.
1641 * E.g., We may see a partial loop like:
1643 * A -> B -> C -> D -> B
1645 * Cutting B->C breaks the cycle. But now the depth of A is
1646 * only 1, and our total_depth counter is at 3. The size of the
1647 * error is always one less than the size of the cycle we
1648 * broke. Commits C and D were "lost" from A's chain.
1650 * If we instead cut D->B, then the depth of A is correct at 3.
1651 * We keep all commits in the chain that we examined.
1653 cur->dfs_state = DFS_ACTIVE;
1654 if (cur->delta->dfs_state == DFS_ACTIVE) {
1655 drop_reused_delta(cur);
1656 cur->dfs_state = DFS_DONE;
1662 * And now that we've gone all the way to the bottom of the chain, we
1663 * need to clear the active flags and set the depth fields as
1664 * appropriate. Unlike the loop above, which can quit when it drops a
1665 * delta, we need to keep going to look for more depth cuts. So we need
1666 * an extra "next" pointer to keep going after we reset cur->delta.
1668 for (cur = entry; cur; cur = next) {
1672 * We should have a chain of zero or more ACTIVE states down to
1673 * a final DONE. We can quit after the DONE, because either it
1674 * has no bases, or we've already handled them in a previous
1677 if (cur->dfs_state == DFS_DONE)
1679 else if (cur->dfs_state != DFS_ACTIVE)
1680 die("BUG: confusing delta dfs state in second pass: %d",
1684 * If the total_depth is more than depth, then we need to snip
1685 * the chain into two or more smaller chains that don't exceed
1686 * the maximum depth. Most of the resulting chains will contain
1687 * (depth + 1) entries (i.e., depth deltas plus one base), and
1688 * the last chain (i.e., the one containing entry) will contain
1689 * whatever entries are left over, namely
1690 * (total_depth % (depth + 1)) of them.
1692 * Since we are iterating towards decreasing depth, we need to
1693 * decrement total_depth as we go, and we need to write to the
1694 * entry what its final depth will be after all of the
1695 * snipping. Since we're snipping into chains of length (depth
1696 * + 1) entries, the final depth of an entry will be its
1697 * original depth modulo (depth + 1). Any time we encounter an
1698 * entry whose final depth is supposed to be zero, we snip it
1699 * from its delta base, thereby making it so.
1701 cur->depth = (total_depth--) % (depth + 1);
1703 drop_reused_delta(cur);
1705 cur->dfs_state = DFS_DONE;
1709 static void get_object_details(void)
1712 struct object_entry **sorted_by_offset;
1714 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1715 for (i = 0; i < to_pack.nr_objects; i++)
1716 sorted_by_offset[i] = to_pack.objects + i;
1717 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1719 for (i = 0; i < to_pack.nr_objects; i++) {
1720 struct object_entry *entry = sorted_by_offset[i];
1721 check_object(entry);
1722 if (big_file_threshold < entry->size)
1723 entry->no_try_delta = 1;
1727 * This must happen in a second pass, since we rely on the delta
1728 * information for the whole list being completed.
1730 for (i = 0; i < to_pack.nr_objects; i++)
1731 break_delta_chains(&to_pack.objects[i]);
1733 free(sorted_by_offset);
1737 * We search for deltas in a list sorted by type, by filename hash, and then
1738 * by size, so that we see progressively smaller and smaller files.
1739 * That's because we prefer deltas to be from the bigger file
1740 * to the smaller -- deletes are potentially cheaper, but perhaps
1741 * more importantly, the bigger file is likely the more recent
1742 * one. The deepest deltas are therefore the oldest objects which are
1743 * less susceptible to be accessed often.
1745 static int type_size_sort(const void *_a, const void *_b)
1747 const struct object_entry *a = *(struct object_entry **)_a;
1748 const struct object_entry *b = *(struct object_entry **)_b;
1750 if (a->type > b->type)
1752 if (a->type < b->type)
1754 if (a->hash > b->hash)
1756 if (a->hash < b->hash)
1758 if (a->preferred_base > b->preferred_base)
1760 if (a->preferred_base < b->preferred_base)
1762 if (a->size > b->size)
1764 if (a->size < b->size)
1766 return a < b ? -1 : (a > b); /* newest first */
1770 struct object_entry *entry;
1772 struct delta_index *index;
1776 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1777 unsigned long delta_size)
1779 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1782 if (delta_size < cache_max_small_delta_size)
1785 /* cache delta, if objects are large enough compared to delta size */
1786 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1794 static pthread_mutex_t read_mutex;
1795 #define read_lock() pthread_mutex_lock(&read_mutex)
1796 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1798 static pthread_mutex_t cache_mutex;
1799 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1800 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1802 static pthread_mutex_t progress_mutex;
1803 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1804 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1808 #define read_lock() (void)0
1809 #define read_unlock() (void)0
1810 #define cache_lock() (void)0
1811 #define cache_unlock() (void)0
1812 #define progress_lock() (void)0
1813 #define progress_unlock() (void)0
1817 static int try_delta(struct unpacked *trg, struct unpacked *src,
1818 unsigned max_depth, unsigned long *mem_usage)
1820 struct object_entry *trg_entry = trg->entry;
1821 struct object_entry *src_entry = src->entry;
1822 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1824 enum object_type type;
1827 /* Don't bother doing diffs between different types */
1828 if (trg_entry->type != src_entry->type)
1832 * We do not bother to try a delta that we discarded on an
1833 * earlier try, but only when reusing delta data. Note that
1834 * src_entry that is marked as the preferred_base should always
1835 * be considered, as even if we produce a suboptimal delta against
1836 * it, we will still save the transfer cost, as we already know
1837 * the other side has it and we won't send src_entry at all.
1839 if (reuse_delta && trg_entry->in_pack &&
1840 trg_entry->in_pack == src_entry->in_pack &&
1841 !src_entry->preferred_base &&
1842 trg_entry->in_pack_type != OBJ_REF_DELTA &&
1843 trg_entry->in_pack_type != OBJ_OFS_DELTA)
1846 /* Let's not bust the allowed depth. */
1847 if (src->depth >= max_depth)
1850 /* Now some size filtering heuristics. */
1851 trg_size = trg_entry->size;
1852 if (!trg_entry->delta) {
1853 max_size = trg_size/2 - 20;
1856 max_size = trg_entry->delta_size;
1857 ref_depth = trg->depth;
1859 max_size = (uint64_t)max_size * (max_depth - src->depth) /
1860 (max_depth - ref_depth + 1);
1863 src_size = src_entry->size;
1864 sizediff = src_size < trg_size ? trg_size - src_size : 0;
1865 if (sizediff >= max_size)
1867 if (trg_size < src_size / 32)
1870 /* Load data if not already done */
1873 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
1876 die("object %s cannot be read",
1877 oid_to_hex(&trg_entry->idx.oid));
1879 die("object %s inconsistent object length (%lu vs %lu)",
1880 oid_to_hex(&trg_entry->idx.oid), sz,
1886 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
1889 if (src_entry->preferred_base) {
1890 static int warned = 0;
1892 warning("object %s cannot be read",
1893 oid_to_hex(&src_entry->idx.oid));
1895 * Those objects are not included in the
1896 * resulting pack. Be resilient and ignore
1897 * them if they can't be read, in case the
1898 * pack could be created nevertheless.
1902 die("object %s cannot be read",
1903 oid_to_hex(&src_entry->idx.oid));
1906 die("object %s inconsistent object length (%lu vs %lu)",
1907 oid_to_hex(&src_entry->idx.oid), sz,
1912 src->index = create_delta_index(src->data, src_size);
1914 static int warned = 0;
1916 warning("suboptimal pack - out of memory");
1919 *mem_usage += sizeof_delta_index(src->index);
1922 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1926 if (trg_entry->delta) {
1927 /* Prefer only shallower same-sized deltas. */
1928 if (delta_size == trg_entry->delta_size &&
1929 src->depth + 1 >= trg->depth) {
1936 * Handle memory allocation outside of the cache
1937 * accounting lock. Compiler will optimize the strangeness
1938 * away when NO_PTHREADS is defined.
1940 free(trg_entry->delta_data);
1942 if (trg_entry->delta_data) {
1943 delta_cache_size -= trg_entry->delta_size;
1944 trg_entry->delta_data = NULL;
1946 if (delta_cacheable(src_size, trg_size, delta_size)) {
1947 delta_cache_size += delta_size;
1949 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
1955 trg_entry->delta = src_entry;
1956 trg_entry->delta_size = delta_size;
1957 trg->depth = src->depth + 1;
1962 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
1964 struct object_entry *child = me->delta_child;
1967 unsigned int c = check_delta_limit(child, n + 1);
1970 child = child->delta_sibling;
1975 static unsigned long free_unpacked(struct unpacked *n)
1977 unsigned long freed_mem = sizeof_delta_index(n->index);
1978 free_delta_index(n->index);
1981 freed_mem += n->entry->size;
1982 FREE_AND_NULL(n->data);
1989 static void find_deltas(struct object_entry **list, unsigned *list_size,
1990 int window, int depth, unsigned *processed)
1992 uint32_t i, idx = 0, count = 0;
1993 struct unpacked *array;
1994 unsigned long mem_usage = 0;
1996 array = xcalloc(window, sizeof(struct unpacked));
1999 struct object_entry *entry;
2000 struct unpacked *n = array + idx;
2001 int j, max_depth, best_base = -1;
2010 if (!entry->preferred_base) {
2012 display_progress(progress_state, *processed);
2016 mem_usage -= free_unpacked(n);
2019 while (window_memory_limit &&
2020 mem_usage > window_memory_limit &&
2022 uint32_t tail = (idx + window - count) % window;
2023 mem_usage -= free_unpacked(array + tail);
2027 /* We do not compute delta to *create* objects we are not
2030 if (entry->preferred_base)
2034 * If the current object is at pack edge, take the depth the
2035 * objects that depend on the current object into account
2036 * otherwise they would become too deep.
2039 if (entry->delta_child) {
2040 max_depth -= check_delta_limit(entry, 0);
2048 uint32_t other_idx = idx + j;
2050 if (other_idx >= window)
2051 other_idx -= window;
2052 m = array + other_idx;
2055 ret = try_delta(n, m, max_depth, &mem_usage);
2059 best_base = other_idx;
2063 * If we decided to cache the delta data, then it is best
2064 * to compress it right away. First because we have to do
2065 * it anyway, and doing it here while we're threaded will
2066 * save a lot of time in the non threaded write phase,
2067 * as well as allow for caching more deltas within
2068 * the same cache size limit.
2070 * But only if not writing to stdout, since in that case
2071 * the network is most likely throttling writes anyway,
2072 * and therefore it is best to go to the write phase ASAP
2073 * instead, as we can afford spending more time compressing
2074 * between writes at that moment.
2076 if (entry->delta_data && !pack_to_stdout) {
2077 entry->z_delta_size = do_compress(&entry->delta_data,
2080 delta_cache_size -= entry->delta_size;
2081 delta_cache_size += entry->z_delta_size;
2085 /* if we made n a delta, and if n is already at max
2086 * depth, leaving it in the window is pointless. we
2087 * should evict it first.
2089 if (entry->delta && max_depth <= n->depth)
2093 * Move the best delta base up in the window, after the
2094 * currently deltified object, to keep it longer. It will
2095 * be the first base object to be attempted next.
2098 struct unpacked swap = array[best_base];
2099 int dist = (window + idx - best_base) % window;
2100 int dst = best_base;
2102 int src = (dst + 1) % window;
2103 array[dst] = array[src];
2111 if (count + 1 < window)
2117 for (i = 0; i < window; ++i) {
2118 free_delta_index(array[i].index);
2119 free(array[i].data);
2126 static void try_to_free_from_threads(size_t size)
2129 release_pack_memory(size);
2133 static try_to_free_t old_try_to_free_routine;
2136 * The main thread waits on the condition that (at least) one of the workers
2137 * has stopped working (which is indicated in the .working member of
2138 * struct thread_params).
2139 * When a work thread has completed its work, it sets .working to 0 and
2140 * signals the main thread and waits on the condition that .data_ready
2144 struct thread_params {
2146 struct object_entry **list;
2153 pthread_mutex_t mutex;
2154 pthread_cond_t cond;
2155 unsigned *processed;
2158 static pthread_cond_t progress_cond;
2161 * Mutex and conditional variable can't be statically-initialized on Windows.
2163 static void init_threaded_search(void)
2165 init_recursive_mutex(&read_mutex);
2166 pthread_mutex_init(&cache_mutex, NULL);
2167 pthread_mutex_init(&progress_mutex, NULL);
2168 pthread_cond_init(&progress_cond, NULL);
2169 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2172 static void cleanup_threaded_search(void)
2174 set_try_to_free_routine(old_try_to_free_routine);
2175 pthread_cond_destroy(&progress_cond);
2176 pthread_mutex_destroy(&read_mutex);
2177 pthread_mutex_destroy(&cache_mutex);
2178 pthread_mutex_destroy(&progress_mutex);
2181 static void *threaded_find_deltas(void *arg)
2183 struct thread_params *me = arg;
2186 while (me->remaining) {
2189 find_deltas(me->list, &me->remaining,
2190 me->window, me->depth, me->processed);
2194 pthread_cond_signal(&progress_cond);
2198 * We must not set ->data_ready before we wait on the
2199 * condition because the main thread may have set it to 1
2200 * before we get here. In order to be sure that new
2201 * work is available if we see 1 in ->data_ready, it
2202 * was initialized to 0 before this thread was spawned
2203 * and we reset it to 0 right away.
2205 pthread_mutex_lock(&me->mutex);
2206 while (!me->data_ready)
2207 pthread_cond_wait(&me->cond, &me->mutex);
2209 pthread_mutex_unlock(&me->mutex);
2214 /* leave ->working 1 so that this doesn't get more work assigned */
2218 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2219 int window, int depth, unsigned *processed)
2221 struct thread_params *p;
2222 int i, ret, active_threads = 0;
2224 init_threaded_search();
2226 if (delta_search_threads <= 1) {
2227 find_deltas(list, &list_size, window, depth, processed);
2228 cleanup_threaded_search();
2231 if (progress > pack_to_stdout)
2232 fprintf(stderr, "Delta compression using up to %d threads.\n",
2233 delta_search_threads);
2234 p = xcalloc(delta_search_threads, sizeof(*p));
2236 /* Partition the work amongst work threads. */
2237 for (i = 0; i < delta_search_threads; i++) {
2238 unsigned sub_size = list_size / (delta_search_threads - i);
2240 /* don't use too small segments or no deltas will be found */
2241 if (sub_size < 2*window && i+1 < delta_search_threads)
2244 p[i].window = window;
2246 p[i].processed = processed;
2248 p[i].data_ready = 0;
2250 /* try to split chunks on "path" boundaries */
2251 while (sub_size && sub_size < list_size &&
2252 list[sub_size]->hash &&
2253 list[sub_size]->hash == list[sub_size-1]->hash)
2257 p[i].list_size = sub_size;
2258 p[i].remaining = sub_size;
2261 list_size -= sub_size;
2264 /* Start work threads. */
2265 for (i = 0; i < delta_search_threads; i++) {
2266 if (!p[i].list_size)
2268 pthread_mutex_init(&p[i].mutex, NULL);
2269 pthread_cond_init(&p[i].cond, NULL);
2270 ret = pthread_create(&p[i].thread, NULL,
2271 threaded_find_deltas, &p[i]);
2273 die("unable to create thread: %s", strerror(ret));
2278 * Now let's wait for work completion. Each time a thread is done
2279 * with its work, we steal half of the remaining work from the
2280 * thread with the largest number of unprocessed objects and give
2281 * it to that newly idle thread. This ensure good load balancing
2282 * until the remaining object list segments are simply too short
2283 * to be worth splitting anymore.
2285 while (active_threads) {
2286 struct thread_params *target = NULL;
2287 struct thread_params *victim = NULL;
2288 unsigned sub_size = 0;
2292 for (i = 0; !target && i < delta_search_threads; i++)
2297 pthread_cond_wait(&progress_cond, &progress_mutex);
2300 for (i = 0; i < delta_search_threads; i++)
2301 if (p[i].remaining > 2*window &&
2302 (!victim || victim->remaining < p[i].remaining))
2305 sub_size = victim->remaining / 2;
2306 list = victim->list + victim->list_size - sub_size;
2307 while (sub_size && list[0]->hash &&
2308 list[0]->hash == list[-1]->hash) {
2314 * It is possible for some "paths" to have
2315 * so many objects that no hash boundary
2316 * might be found. Let's just steal the
2317 * exact half in that case.
2319 sub_size = victim->remaining / 2;
2322 target->list = list;
2323 victim->list_size -= sub_size;
2324 victim->remaining -= sub_size;
2326 target->list_size = sub_size;
2327 target->remaining = sub_size;
2328 target->working = 1;
2331 pthread_mutex_lock(&target->mutex);
2332 target->data_ready = 1;
2333 pthread_cond_signal(&target->cond);
2334 pthread_mutex_unlock(&target->mutex);
2337 pthread_join(target->thread, NULL);
2338 pthread_cond_destroy(&target->cond);
2339 pthread_mutex_destroy(&target->mutex);
2343 cleanup_threaded_search();
2348 #define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)
2351 static void add_tag_chain(const struct object_id *oid)
2356 * We catch duplicates already in add_object_entry(), but we'd
2357 * prefer to do this extra check to avoid having to parse the
2358 * tag at all if we already know that it's being packed (e.g., if
2359 * it was included via bitmaps, we would not have parsed it
2362 if (packlist_find(&to_pack, oid->hash, NULL))
2365 tag = lookup_tag(oid);
2367 if (!tag || parse_tag(tag) || !tag->tagged)
2368 die("unable to pack objects reachable from tag %s",
2371 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2373 if (tag->tagged->type != OBJ_TAG)
2376 tag = (struct tag *)tag->tagged;
2380 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2382 struct object_id peeled;
2384 if (starts_with(path, "refs/tags/") && /* is a tag? */
2385 !peel_ref(path, &peeled) && /* peelable? */
2386 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */
2391 static void prepare_pack(int window, int depth)
2393 struct object_entry **delta_list;
2394 uint32_t i, nr_deltas;
2397 get_object_details();
2400 * If we're locally repacking then we need to be doubly careful
2401 * from now on in order to make sure no stealth corruption gets
2402 * propagated to the new pack. Clients receiving streamed packs
2403 * should validate everything they get anyway so no need to incur
2404 * the additional cost here in that case.
2406 if (!pack_to_stdout)
2407 do_check_packed_object_crc = 1;
2409 if (!to_pack.nr_objects || !window || !depth)
2412 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2415 for (i = 0; i < to_pack.nr_objects; i++) {
2416 struct object_entry *entry = to_pack.objects + i;
2419 /* This happens if we decided to reuse existing
2420 * delta from a pack. "reuse_delta &&" is implied.
2424 if (entry->size < 50)
2427 if (entry->no_try_delta)
2430 if (!entry->preferred_base) {
2432 if (entry->type < 0)
2433 die("unable to get type of object %s",
2434 oid_to_hex(&entry->idx.oid));
2436 if (entry->type < 0) {
2438 * This object is not found, but we
2439 * don't have to include it anyway.
2445 delta_list[n++] = entry;
2448 if (nr_deltas && n > 1) {
2449 unsigned nr_done = 0;
2451 progress_state = start_progress(_("Compressing objects"),
2453 QSORT(delta_list, n, type_size_sort);
2454 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2455 stop_progress(&progress_state);
2456 if (nr_done != nr_deltas)
2457 die("inconsistency with delta count");
2462 static int git_pack_config(const char *k, const char *v, void *cb)
2464 if (!strcmp(k, "pack.window")) {
2465 window = git_config_int(k, v);
2468 if (!strcmp(k, "pack.windowmemory")) {
2469 window_memory_limit = git_config_ulong(k, v);
2472 if (!strcmp(k, "pack.depth")) {
2473 depth = git_config_int(k, v);
2476 if (!strcmp(k, "pack.deltacachesize")) {
2477 max_delta_cache_size = git_config_int(k, v);
2480 if (!strcmp(k, "pack.deltacachelimit")) {
2481 cache_max_small_delta_size = git_config_int(k, v);
2484 if (!strcmp(k, "pack.writebitmaphashcache")) {
2485 if (git_config_bool(k, v))
2486 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2488 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2490 if (!strcmp(k, "pack.usebitmaps")) {
2491 use_bitmap_index_default = git_config_bool(k, v);
2494 if (!strcmp(k, "pack.threads")) {
2495 delta_search_threads = git_config_int(k, v);
2496 if (delta_search_threads < 0)
2497 die("invalid number of threads specified (%d)",
2498 delta_search_threads);
2500 if (delta_search_threads != 1) {
2501 warning("no threads support, ignoring %s", k);
2502 delta_search_threads = 0;
2507 if (!strcmp(k, "pack.indexversion")) {
2508 pack_idx_opts.version = git_config_int(k, v);
2509 if (pack_idx_opts.version > 2)
2510 die("bad pack.indexversion=%"PRIu32,
2511 pack_idx_opts.version);
2514 return git_default_config(k, v, cb);
2517 static void read_object_list_from_stdin(void)
2519 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2520 struct object_id oid;
2524 if (!fgets(line, sizeof(line), stdin)) {
2528 die("fgets returned NULL, not EOF, not error!");
2534 if (line[0] == '-') {
2535 if (get_oid_hex(line+1, &oid))
2536 die("expected edge object ID, got garbage:\n %s",
2538 add_preferred_base(&oid);
2541 if (parse_oid_hex(line, &oid, &p))
2542 die("expected object ID, got garbage:\n %s", line);
2544 add_preferred_base_object(p + 1);
2545 add_object_entry(&oid, 0, p + 1, 0);
2549 /* Remember to update object flag allocation in object.h */
2550 #define OBJECT_ADDED (1u<<20)
2552 static void show_commit(struct commit *commit, void *data)
2554 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2555 commit->object.flags |= OBJECT_ADDED;
2557 if (write_bitmap_index)
2558 index_commit_for_bitmap(commit);
2561 static void show_object(struct object *obj, const char *name, void *data)
2563 add_preferred_base_object(name);
2564 add_object_entry(&obj->oid, obj->type, name, 0);
2565 obj->flags |= OBJECT_ADDED;
2568 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2570 assert(arg_missing_action == MA_ALLOW_ANY);
2573 * Quietly ignore ALL missing objects. This avoids problems with
2574 * staging them now and getting an odd error later.
2576 if (!has_object_file(&obj->oid))
2579 show_object(obj, name, data);
2582 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2584 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2587 * Quietly ignore EXPECTED missing objects. This avoids problems with
2588 * staging them now and getting an odd error later.
2590 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2593 show_object(obj, name, data);
2596 static int option_parse_missing_action(const struct option *opt,
2597 const char *arg, int unset)
2602 if (!strcmp(arg, "error")) {
2603 arg_missing_action = MA_ERROR;
2604 fn_show_object = show_object;
2608 if (!strcmp(arg, "allow-any")) {
2609 arg_missing_action = MA_ALLOW_ANY;
2610 fetch_if_missing = 0;
2611 fn_show_object = show_object__ma_allow_any;
2615 if (!strcmp(arg, "allow-promisor")) {
2616 arg_missing_action = MA_ALLOW_PROMISOR;
2617 fetch_if_missing = 0;
2618 fn_show_object = show_object__ma_allow_promisor;
2622 die(_("invalid value for --missing"));
2626 static void show_edge(struct commit *commit)
2628 add_preferred_base(&commit->object.oid);
2631 struct in_pack_object {
2633 struct object *object;
2639 struct in_pack_object *array;
2642 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2644 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2645 in_pack->array[in_pack->nr].object = object;
2650 * Compare the objects in the offset order, in order to emulate the
2651 * "git rev-list --objects" output that produced the pack originally.
2653 static int ofscmp(const void *a_, const void *b_)
2655 struct in_pack_object *a = (struct in_pack_object *)a_;
2656 struct in_pack_object *b = (struct in_pack_object *)b_;
2658 if (a->offset < b->offset)
2660 else if (a->offset > b->offset)
2663 return oidcmp(&a->object->oid, &b->object->oid);
2666 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2668 struct packed_git *p;
2669 struct in_pack in_pack;
2672 memset(&in_pack, 0, sizeof(in_pack));
2674 for (p = get_packed_git(the_repository); p; p = p->next) {
2675 struct object_id oid;
2678 if (!p->pack_local || p->pack_keep)
2680 if (open_pack_index(p))
2681 die("cannot open pack index");
2683 ALLOC_GROW(in_pack.array,
2684 in_pack.nr + p->num_objects,
2687 for (i = 0; i < p->num_objects; i++) {
2688 nth_packed_object_oid(&oid, p, i);
2689 o = lookup_unknown_object(oid.hash);
2690 if (!(o->flags & OBJECT_ADDED))
2691 mark_in_pack_object(o, p, &in_pack);
2692 o->flags |= OBJECT_ADDED;
2697 QSORT(in_pack.array, in_pack.nr, ofscmp);
2698 for (i = 0; i < in_pack.nr; i++) {
2699 struct object *o = in_pack.array[i].object;
2700 add_object_entry(&o->oid, o->type, "", 0);
2703 free(in_pack.array);
2706 static int add_loose_object(const struct object_id *oid, const char *path,
2709 enum object_type type = oid_object_info(oid, NULL);
2712 warning("loose object at %s could not be examined", path);
2716 add_object_entry(oid, type, "", 0);
2721 * We actually don't even have to worry about reachability here.
2722 * add_object_entry will weed out duplicates, so we just add every
2723 * loose object we find.
2725 static void add_unreachable_loose_objects(void)
2727 for_each_loose_file_in_objdir(get_object_directory(),
2732 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2734 static struct packed_git *last_found = (void *)1;
2735 struct packed_git *p;
2737 p = (last_found != (void *)1) ? last_found :
2738 get_packed_git(the_repository);
2741 if ((!p->pack_local || p->pack_keep) &&
2742 find_pack_entry_one(oid->hash, p)) {
2746 if (p == last_found)
2747 p = get_packed_git(the_repository);
2750 if (p == last_found)
2757 * Store a list of sha1s that are should not be discarded
2758 * because they are either written too recently, or are
2759 * reachable from another object that was.
2761 * This is filled by get_object_list.
2763 static struct oid_array recent_objects;
2765 static int loosened_object_can_be_discarded(const struct object_id *oid,
2768 if (!unpack_unreachable_expiration)
2770 if (mtime > unpack_unreachable_expiration)
2772 if (oid_array_lookup(&recent_objects, oid) >= 0)
2777 static void loosen_unused_packed_objects(struct rev_info *revs)
2779 struct packed_git *p;
2781 struct object_id oid;
2783 for (p = get_packed_git(the_repository); p; p = p->next) {
2784 if (!p->pack_local || p->pack_keep)
2787 if (open_pack_index(p))
2788 die("cannot open pack index");
2790 for (i = 0; i < p->num_objects; i++) {
2791 nth_packed_object_oid(&oid, p, i);
2792 if (!packlist_find(&to_pack, oid.hash, NULL) &&
2793 !has_sha1_pack_kept_or_nonlocal(&oid) &&
2794 !loosened_object_can_be_discarded(&oid, p->mtime))
2795 if (force_object_loose(&oid, p->mtime))
2796 die("unable to force loose object");
2802 * This tracks any options which pack-reuse code expects to be on, or which a
2803 * reader of the pack might not understand, and which would therefore prevent
2804 * blind reuse of what we have on disk.
2806 static int pack_options_allow_reuse(void)
2808 return pack_to_stdout &&
2810 !ignore_packed_keep &&
2811 (!local || !have_non_local_packs) &&
2815 static int get_object_list_from_bitmap(struct rev_info *revs)
2817 if (prepare_bitmap_walk(revs) < 0)
2820 if (pack_options_allow_reuse() &&
2821 !reuse_partial_packfile_from_bitmap(
2823 &reuse_packfile_objects,
2824 &reuse_packfile_offset)) {
2825 assert(reuse_packfile_objects);
2826 nr_result += reuse_packfile_objects;
2827 display_progress(progress_state, nr_result);
2830 traverse_bitmap_commit_list(&add_object_entry_from_bitmap);
2834 static void record_recent_object(struct object *obj,
2838 oid_array_append(&recent_objects, &obj->oid);
2841 static void record_recent_commit(struct commit *commit, void *data)
2843 oid_array_append(&recent_objects, &commit->object.oid);
2846 static void get_object_list(int ac, const char **av)
2848 struct rev_info revs;
2852 init_revisions(&revs, NULL);
2853 save_commit_buffer = 0;
2854 setup_revisions(ac, av, &revs, NULL);
2856 /* make sure shallows are read */
2857 is_repository_shallow();
2859 while (fgets(line, sizeof(line), stdin) != NULL) {
2860 int len = strlen(line);
2861 if (len && line[len - 1] == '\n')
2866 if (!strcmp(line, "--not")) {
2867 flags ^= UNINTERESTING;
2868 write_bitmap_index = 0;
2871 if (starts_with(line, "--shallow ")) {
2872 struct object_id oid;
2873 if (get_oid_hex(line + 10, &oid))
2874 die("not an SHA-1 '%s'", line + 10);
2875 register_shallow(&oid);
2876 use_bitmap_index = 0;
2879 die("not a rev '%s'", line);
2881 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
2882 die("bad revision '%s'", line);
2885 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
2888 if (prepare_revision_walk(&revs))
2889 die("revision walk setup failed");
2890 mark_edges_uninteresting(&revs, show_edge);
2892 if (!fn_show_object)
2893 fn_show_object = show_object;
2894 traverse_commit_list_filtered(&filter_options, &revs,
2895 show_commit, fn_show_object, NULL,
2898 if (unpack_unreachable_expiration) {
2899 revs.ignore_missing_links = 1;
2900 if (add_unseen_recent_objects_to_traversal(&revs,
2901 unpack_unreachable_expiration))
2902 die("unable to add recent objects");
2903 if (prepare_revision_walk(&revs))
2904 die("revision walk setup failed");
2905 traverse_commit_list(&revs, record_recent_commit,
2906 record_recent_object, NULL);
2909 if (keep_unreachable)
2910 add_objects_in_unpacked_packs(&revs);
2911 if (pack_loose_unreachable)
2912 add_unreachable_loose_objects();
2913 if (unpack_unreachable)
2914 loosen_unused_packed_objects(&revs);
2916 oid_array_clear(&recent_objects);
2919 static int option_parse_index_version(const struct option *opt,
2920 const char *arg, int unset)
2923 const char *val = arg;
2924 pack_idx_opts.version = strtoul(val, &c, 10);
2925 if (pack_idx_opts.version > 2)
2926 die(_("unsupported index version %s"), val);
2927 if (*c == ',' && c[1])
2928 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
2929 if (*c || pack_idx_opts.off32_limit & 0x80000000)
2930 die(_("bad index version '%s'"), val);
2934 static int option_parse_unpack_unreachable(const struct option *opt,
2935 const char *arg, int unset)
2938 unpack_unreachable = 0;
2939 unpack_unreachable_expiration = 0;
2942 unpack_unreachable = 1;
2944 unpack_unreachable_expiration = approxidate(arg);
2949 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
2951 int use_internal_rev_list = 0;
2954 int all_progress_implied = 0;
2955 struct argv_array rp = ARGV_ARRAY_INIT;
2956 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
2957 int rev_list_index = 0;
2958 struct option pack_objects_options[] = {
2959 OPT_SET_INT('q', "quiet", &progress,
2960 N_("do not show progress meter"), 0),
2961 OPT_SET_INT(0, "progress", &progress,
2962 N_("show progress meter"), 1),
2963 OPT_SET_INT(0, "all-progress", &progress,
2964 N_("show progress meter during object writing phase"), 2),
2965 OPT_BOOL(0, "all-progress-implied",
2966 &all_progress_implied,
2967 N_("similar to --all-progress when progress meter is shown")),
2968 { OPTION_CALLBACK, 0, "index-version", NULL, N_("version[,offset]"),
2969 N_("write the pack index file in the specified idx format version"),
2970 0, option_parse_index_version },
2971 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
2972 N_("maximum size of each output pack file")),
2973 OPT_BOOL(0, "local", &local,
2974 N_("ignore borrowed objects from alternate object store")),
2975 OPT_BOOL(0, "incremental", &incremental,
2976 N_("ignore packed objects")),
2977 OPT_INTEGER(0, "window", &window,
2978 N_("limit pack window by objects")),
2979 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
2980 N_("limit pack window by memory in addition to object limit")),
2981 OPT_INTEGER(0, "depth", &depth,
2982 N_("maximum length of delta chain allowed in the resulting pack")),
2983 OPT_BOOL(0, "reuse-delta", &reuse_delta,
2984 N_("reuse existing deltas")),
2985 OPT_BOOL(0, "reuse-object", &reuse_object,
2986 N_("reuse existing objects")),
2987 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
2988 N_("use OFS_DELTA objects")),
2989 OPT_INTEGER(0, "threads", &delta_search_threads,
2990 N_("use threads when searching for best delta matches")),
2991 OPT_BOOL(0, "non-empty", &non_empty,
2992 N_("do not create an empty pack output")),
2993 OPT_BOOL(0, "revs", &use_internal_rev_list,
2994 N_("read revision arguments from standard input")),
2995 { OPTION_SET_INT, 0, "unpacked", &rev_list_unpacked, NULL,
2996 N_("limit the objects to those that are not yet packed"),
2997 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
2998 { OPTION_SET_INT, 0, "all", &rev_list_all, NULL,
2999 N_("include objects reachable from any reference"),
3000 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
3001 { OPTION_SET_INT, 0, "reflog", &rev_list_reflog, NULL,
3002 N_("include objects referred by reflog entries"),
3003 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
3004 { OPTION_SET_INT, 0, "indexed-objects", &rev_list_index, NULL,
3005 N_("include objects referred to by the index"),
3006 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
3007 OPT_BOOL(0, "stdout", &pack_to_stdout,
3008 N_("output pack to stdout")),
3009 OPT_BOOL(0, "include-tag", &include_tag,
3010 N_("include tag objects that refer to objects to be packed")),
3011 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3012 N_("keep unreachable objects")),
3013 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3014 N_("pack loose unreachable objects")),
3015 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3016 N_("unpack unreachable objects newer than <time>"),
3017 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3018 OPT_BOOL(0, "thin", &thin,
3019 N_("create thin packs")),
3020 OPT_BOOL(0, "shallow", &shallow,
3021 N_("create packs suitable for shallow fetches")),
3022 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep,
3023 N_("ignore packs that have companion .keep file")),
3024 OPT_INTEGER(0, "compression", &pack_compression_level,
3025 N_("pack compression level")),
3026 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3027 N_("do not hide commits by grafts"), 0),
3028 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3029 N_("use a bitmap index if available to speed up counting objects")),
3030 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3031 N_("write a bitmap index together with the pack index")),
3032 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3033 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3034 N_("handling for missing objects"), PARSE_OPT_NONEG,
3035 option_parse_missing_action },
3036 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3037 N_("do not pack objects in promisor packfiles")),
3041 check_replace_refs = 0;
3043 reset_pack_idx_option(&pack_idx_opts);
3044 git_config(git_pack_config, NULL);
3046 progress = isatty(2);
3047 argc = parse_options(argc, argv, prefix, pack_objects_options,
3051 base_name = argv[0];
3054 if (pack_to_stdout != !base_name || argc)
3055 usage_with_options(pack_usage, pack_objects_options);
3057 argv_array_push(&rp, "pack-objects");
3059 use_internal_rev_list = 1;
3060 argv_array_push(&rp, shallow
3061 ? "--objects-edge-aggressive"
3062 : "--objects-edge");
3064 argv_array_push(&rp, "--objects");
3067 use_internal_rev_list = 1;
3068 argv_array_push(&rp, "--all");
3070 if (rev_list_reflog) {
3071 use_internal_rev_list = 1;
3072 argv_array_push(&rp, "--reflog");
3074 if (rev_list_index) {
3075 use_internal_rev_list = 1;
3076 argv_array_push(&rp, "--indexed-objects");
3078 if (rev_list_unpacked) {
3079 use_internal_rev_list = 1;
3080 argv_array_push(&rp, "--unpacked");
3083 if (exclude_promisor_objects) {
3084 use_internal_rev_list = 1;
3085 fetch_if_missing = 0;
3086 argv_array_push(&rp, "--exclude-promisor-objects");
3091 if (pack_compression_level == -1)
3092 pack_compression_level = Z_DEFAULT_COMPRESSION;
3093 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3094 die("bad pack compression level %d", pack_compression_level);
3096 if (!delta_search_threads) /* --threads=0 means autodetect */
3097 delta_search_threads = online_cpus();
3100 if (delta_search_threads != 1)
3101 warning("no threads support, ignoring --threads");
3103 if (!pack_to_stdout && !pack_size_limit)
3104 pack_size_limit = pack_size_limit_cfg;
3105 if (pack_to_stdout && pack_size_limit)
3106 die("--max-pack-size cannot be used to build a pack for transfer.");
3107 if (pack_size_limit && pack_size_limit < 1024*1024) {
3108 warning("minimum pack size limit is 1 MiB");
3109 pack_size_limit = 1024*1024;
3112 if (!pack_to_stdout && thin)
3113 die("--thin cannot be used to build an indexable pack.");
3115 if (keep_unreachable && unpack_unreachable)
3116 die("--keep-unreachable and --unpack-unreachable are incompatible.");
3117 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3118 unpack_unreachable_expiration = 0;
3120 if (filter_options.choice) {
3121 if (!pack_to_stdout)
3122 die("cannot use --filter without --stdout.");
3123 use_bitmap_index = 0;
3127 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3129 * - to produce good pack (with bitmap index not-yet-packed objects are
3130 * packed in suboptimal order).
3132 * - to use more robust pack-generation codepath (avoiding possible
3133 * bugs in bitmap code and possible bitmap index corruption).
3135 if (!pack_to_stdout)
3136 use_bitmap_index_default = 0;
3138 if (use_bitmap_index < 0)
3139 use_bitmap_index = use_bitmap_index_default;
3141 /* "hard" reasons not to use bitmaps; these just won't work at all */
3142 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow())
3143 use_bitmap_index = 0;
3145 if (pack_to_stdout || !rev_list_all)
3146 write_bitmap_index = 0;
3148 if (progress && all_progress_implied)
3151 if (ignore_packed_keep) {
3152 struct packed_git *p;
3153 for (p = get_packed_git(the_repository); p; p = p->next)
3154 if (p->pack_local && p->pack_keep)
3156 if (!p) /* no keep-able packs found */
3157 ignore_packed_keep = 0;
3161 * unlike ignore_packed_keep above, we do not want to
3162 * unset "local" based on looking at packs, as it
3163 * also covers non-local objects
3165 struct packed_git *p;
3166 for (p = get_packed_git(the_repository); p; p = p->next) {
3167 if (!p->pack_local) {
3168 have_non_local_packs = 1;
3175 progress_state = start_progress(_("Counting objects"), 0);
3176 if (!use_internal_rev_list)
3177 read_object_list_from_stdin();
3179 get_object_list(rp.argc, rp.argv);
3180 argv_array_clear(&rp);
3182 cleanup_preferred_base();
3183 if (include_tag && nr_result)
3184 for_each_ref(add_ref_tag, NULL);
3185 stop_progress(&progress_state);
3187 if (non_empty && !nr_result)
3190 prepare_pack(window, depth);
3193 fprintf(stderr, "Total %"PRIu32" (delta %"PRIu32"),"
3194 " reused %"PRIu32" (delta %"PRIu32")\n",
3195 written, written_delta, reused, reused_delta);