Code

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