Code

eca130f055ca83b839cfbfdf05907df7fdfbc7c3
[git.git] / builtin-pack-objects.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "attr.h"
4 #include "object.h"
5 #include "blob.h"
6 #include "commit.h"
7 #include "tag.h"
8 #include "tree.h"
9 #include "delta.h"
10 #include "pack.h"
11 #include "csum-file.h"
12 #include "tree-walk.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "list-objects.h"
16 #include "progress.h"
18 static const char pack_usage[] = "\
19 git-pack-objects [{ -q | --progress | --all-progress }] \n\
20         [--local] [--incremental] [--window=N] [--depth=N] \n\
21         [--no-reuse-delta] [--no-reuse-object] [--delta-base-offset] \n\
22         [--non-empty] [--revs [--unpacked | --all]*] [--reflog] \n\
23         [--stdout | base-name] [<ref-list | <object-list]";
25 struct object_entry {
26         unsigned char sha1[20];
27         uint32_t crc32;         /* crc of raw pack data for this object */
28         off_t offset;           /* offset into the final pack file */
29         unsigned long size;     /* uncompressed size */
30         unsigned int hash;      /* name hint hash */
31         unsigned int depth;     /* delta depth */
32         struct packed_git *in_pack;     /* already in pack */
33         off_t in_pack_offset;
34         struct object_entry *delta;     /* delta base object */
35         struct object_entry *delta_child; /* deltified objects who bases me */
36         struct object_entry *delta_sibling; /* other deltified objects who
37                                              * uses the same base as me
38                                              */
39         unsigned long delta_size;       /* delta data size (uncompressed) */
40         enum object_type type;
41         enum object_type in_pack_type;  /* could be delta */
42         unsigned char in_pack_header_size;
43         unsigned char preferred_base; /* we do not pack this, but is available
44                                        * to be used as the base object to delta
45                                        * objects against.
46                                        */
47         unsigned char no_try_delta;
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 static struct object_entry *objects;
57 static uint32_t nr_objects, nr_alloc, nr_result;
59 static int non_empty;
60 static int no_reuse_delta, no_reuse_object;
61 static int local;
62 static int incremental;
63 static int allow_ofs_delta;
64 static const char *pack_tmp_name, *idx_tmp_name;
65 static char tmpname[PATH_MAX];
66 static unsigned char pack_file_sha1[20];
67 static int progress = 1;
68 static int window = 10;
69 static int depth = 50;
70 static int pack_to_stdout;
71 static int num_preferred_base;
72 static struct progress progress_state;
73 static int pack_compression_level = Z_DEFAULT_COMPRESSION;
74 static int pack_compression_seen;
76 /*
77  * The object names in objects array are hashed with this hashtable,
78  * to help looking up the entry by object name.
79  * This hashtable is built after all the objects are seen.
80  */
81 static int *object_ix;
82 static int object_ix_hashsz;
84 /*
85  * Pack index for existing packs give us easy access to the offsets into
86  * corresponding pack file where each object's data starts, but the entries
87  * do not store the size of the compressed representation (uncompressed
88  * size is easily available by examining the pack entry header).  It is
89  * also rather expensive to find the sha1 for an object given its offset.
90  *
91  * We build a hashtable of existing packs (pack_revindex), and keep reverse
92  * index here -- pack index file is sorted by object name mapping to offset;
93  * this pack_revindex[].revindex array is a list of offset/index_nr pairs
94  * ordered by offset, so if you know the offset of an object, next offset
95  * is where its packed representation ends and the index_nr can be used to
96  * get the object sha1 from the main index.
97  */
98 struct revindex_entry {
99         off_t offset;
100         unsigned int nr;
101 };
102 struct pack_revindex {
103         struct packed_git *p;
104         struct revindex_entry *revindex;
105 };
106 static struct  pack_revindex *pack_revindex;
107 static int pack_revindex_hashsz;
109 /*
110  * stats
111  */
112 static uint32_t written, written_delta;
113 static uint32_t reused, reused_delta;
115 static int pack_revindex_ix(struct packed_git *p)
117         unsigned long ui = (unsigned long)p;
118         int i;
120         ui = ui ^ (ui >> 16); /* defeat structure alignment */
121         i = (int)(ui % pack_revindex_hashsz);
122         while (pack_revindex[i].p) {
123                 if (pack_revindex[i].p == p)
124                         return i;
125                 if (++i == pack_revindex_hashsz)
126                         i = 0;
127         }
128         return -1 - i;
131 static void prepare_pack_ix(void)
133         int num;
134         struct packed_git *p;
135         for (num = 0, p = packed_git; p; p = p->next)
136                 num++;
137         if (!num)
138                 return;
139         pack_revindex_hashsz = num * 11;
140         pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
141         for (p = packed_git; p; p = p->next) {
142                 num = pack_revindex_ix(p);
143                 num = - 1 - num;
144                 pack_revindex[num].p = p;
145         }
146         /* revindex elements are lazily initialized */
149 static int cmp_offset(const void *a_, const void *b_)
151         const struct revindex_entry *a = a_;
152         const struct revindex_entry *b = b_;
153         return (a->offset < b->offset) ? -1 : (a->offset > b->offset) ? 1 : 0;
156 /*
157  * Ordered list of offsets of objects in the pack.
158  */
159 static void prepare_pack_revindex(struct pack_revindex *rix)
161         struct packed_git *p = rix->p;
162         int num_ent = p->num_objects;
163         int i;
164         const char *index = p->index_data;
166         rix->revindex = xmalloc(sizeof(*rix->revindex) * (num_ent + 1));
167         index += 4 * 256;
169         if (p->index_version > 1) {
170                 const uint32_t *off_32 =
171                         (uint32_t *)(index + 8 + p->num_objects * (20 + 4));
172                 const uint32_t *off_64 = off_32 + p->num_objects;
173                 for (i = 0; i < num_ent; i++) {
174                         uint32_t off = ntohl(*off_32++);
175                         if (!(off & 0x80000000)) {
176                                 rix->revindex[i].offset = off;
177                         } else {
178                                 rix->revindex[i].offset =
179                                         ((uint64_t)ntohl(*off_64++)) << 32;
180                                 rix->revindex[i].offset |=
181                                         ntohl(*off_64++);
182                         }
183                         rix->revindex[i].nr = i;
184                 }
185         } else {
186                 for (i = 0; i < num_ent; i++) {
187                         uint32_t hl = *((uint32_t *)(index + 24 * i));
188                         rix->revindex[i].offset = ntohl(hl);
189                         rix->revindex[i].nr = i;
190                 }
191         }
193         /* This knows the pack format -- the 20-byte trailer
194          * follows immediately after the last object data.
195          */
196         rix->revindex[num_ent].offset = p->pack_size - 20;
197         rix->revindex[num_ent].nr = -1;
198         qsort(rix->revindex, num_ent, sizeof(*rix->revindex), cmp_offset);
201 static struct revindex_entry * find_packed_object(struct packed_git *p,
202                                                   off_t ofs)
204         int num;
205         int lo, hi;
206         struct pack_revindex *rix;
207         struct revindex_entry *revindex;
208         num = pack_revindex_ix(p);
209         if (num < 0)
210                 die("internal error: pack revindex uninitialized");
211         rix = &pack_revindex[num];
212         if (!rix->revindex)
213                 prepare_pack_revindex(rix);
214         revindex = rix->revindex;
215         lo = 0;
216         hi = p->num_objects + 1;
217         do {
218                 int mi = (lo + hi) / 2;
219                 if (revindex[mi].offset == ofs) {
220                         return revindex + mi;
221                 }
222                 else if (ofs < revindex[mi].offset)
223                         hi = mi;
224                 else
225                         lo = mi + 1;
226         } while (lo < hi);
227         die("internal error: pack revindex corrupt");
230 static const unsigned char *find_packed_object_name(struct packed_git *p,
231                                                     off_t ofs)
233         struct revindex_entry *entry = find_packed_object(p, ofs);
234         return nth_packed_object_sha1(p, entry->nr);
237 static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
239         unsigned long othersize, delta_size;
240         enum object_type type;
241         void *otherbuf = read_sha1_file(entry->delta->sha1, &type, &othersize);
242         void *delta_buf;
244         if (!otherbuf)
245                 die("unable to read %s", sha1_to_hex(entry->delta->sha1));
246         delta_buf = diff_delta(otherbuf, othersize,
247                                buf, size, &delta_size, 0);
248         if (!delta_buf || delta_size != entry->delta_size)
249                 die("delta size changed");
250         free(buf);
251         free(otherbuf);
252         return delta_buf;
255 /*
256  * The per-object header is a pretty dense thing, which is
257  *  - first byte: low four bits are "size", then three bits of "type",
258  *    and the high bit is "size continues".
259  *  - each byte afterwards: low seven bits are size continuation,
260  *    with the high bit being "size continues"
261  */
262 static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
264         int n = 1;
265         unsigned char c;
267         if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
268                 die("bad type %d", type);
270         c = (type << 4) | (size & 15);
271         size >>= 4;
272         while (size) {
273                 *hdr++ = c | 0x80;
274                 c = size & 0x7f;
275                 size >>= 7;
276                 n++;
277         }
278         *hdr = c;
279         return n;
282 /*
283  * we are going to reuse the existing object data as is.  make
284  * sure it is not corrupt.
285  */
286 static int check_pack_inflate(struct packed_git *p,
287                 struct pack_window **w_curs,
288                 off_t offset,
289                 off_t len,
290                 unsigned long expect)
292         z_stream stream;
293         unsigned char fakebuf[4096], *in;
294         int st;
296         memset(&stream, 0, sizeof(stream));
297         inflateInit(&stream);
298         do {
299                 in = use_pack(p, w_curs, offset, &stream.avail_in);
300                 stream.next_in = in;
301                 stream.next_out = fakebuf;
302                 stream.avail_out = sizeof(fakebuf);
303                 st = inflate(&stream, Z_FINISH);
304                 offset += stream.next_in - in;
305         } while (st == Z_OK || st == Z_BUF_ERROR);
306         inflateEnd(&stream);
307         return (st == Z_STREAM_END &&
308                 stream.total_out == expect &&
309                 stream.total_in == len) ? 0 : -1;
312 static int check_pack_crc(struct packed_git *p, struct pack_window **w_curs,
313                           off_t offset, off_t len, unsigned int nr)
315         const uint32_t *index_crc;
316         uint32_t data_crc = crc32(0, Z_NULL, 0);
318         do {
319                 unsigned int avail;
320                 void *data = use_pack(p, w_curs, offset, &avail);
321                 if (avail > len)
322                         avail = len;
323                 data_crc = crc32(data_crc, data, avail);
324                 offset += avail;
325                 len -= avail;
326         } while (len);
328         index_crc = p->index_data;
329         index_crc += 2 + 256 + p->num_objects * (20/4) + nr;
331         return data_crc != ntohl(*index_crc);
334 static void copy_pack_data(struct sha1file *f,
335                 struct packed_git *p,
336                 struct pack_window **w_curs,
337                 off_t offset,
338                 off_t len)
340         unsigned char *in;
341         unsigned int avail;
343         while (len) {
344                 in = use_pack(p, w_curs, offset, &avail);
345                 if (avail > len)
346                         avail = (unsigned int)len;
347                 sha1write(f, in, avail);
348                 offset += avail;
349                 len -= avail;
350         }
353 static unsigned long write_object(struct sha1file *f,
354                                   struct object_entry *entry)
356         unsigned long size;
357         enum object_type type;
358         void *buf;
359         unsigned char header[10];
360         unsigned hdrlen;
361         off_t datalen;
362         enum object_type obj_type;
363         int to_reuse = 0;
365         if (!pack_to_stdout)
366                 crc32_begin(f);
368         obj_type = entry->type;
369         if (no_reuse_object)
370                 to_reuse = 0;   /* explicit */
371         else if (!entry->in_pack)
372                 to_reuse = 0;   /* can't reuse what we don't have */
373         else if (obj_type == OBJ_REF_DELTA || obj_type == OBJ_OFS_DELTA)
374                 to_reuse = 1;   /* check_object() decided it for us */
375         else if (obj_type != entry->in_pack_type)
376                 to_reuse = 0;   /* pack has delta which is unusable */
377         else if (entry->delta)
378                 to_reuse = 0;   /* we want to pack afresh */
379         else
380                 to_reuse = 1;   /* we have it in-pack undeltified,
381                                  * and we do not need to deltify it.
382                                  */
384         if (!to_reuse) {
385                 buf = read_sha1_file(entry->sha1, &type, &size);
386                 if (!buf)
387                         die("unable to read %s", sha1_to_hex(entry->sha1));
388                 if (size != entry->size)
389                         die("object %s size inconsistency (%lu vs %lu)",
390                             sha1_to_hex(entry->sha1), size, entry->size);
391                 if (entry->delta) {
392                         buf = delta_against(buf, size, entry);
393                         size = entry->delta_size;
394                         obj_type = (allow_ofs_delta && entry->delta->offset) ?
395                                 OBJ_OFS_DELTA : OBJ_REF_DELTA;
396                 }
397                 /*
398                  * The object header is a byte of 'type' followed by zero or
399                  * more bytes of length.
400                  */
401                 hdrlen = encode_header(obj_type, size, header);
402                 sha1write(f, header, hdrlen);
404                 if (obj_type == OBJ_OFS_DELTA) {
405                         /*
406                          * Deltas with relative base contain an additional
407                          * encoding of the relative offset for the delta
408                          * base from this object's position in the pack.
409                          */
410                         off_t ofs = entry->offset - entry->delta->offset;
411                         unsigned pos = sizeof(header) - 1;
412                         header[pos] = ofs & 127;
413                         while (ofs >>= 7)
414                                 header[--pos] = 128 | (--ofs & 127);
415                         sha1write(f, header + pos, sizeof(header) - pos);
416                         hdrlen += sizeof(header) - pos;
417                 } else if (obj_type == OBJ_REF_DELTA) {
418                         /*
419                          * Deltas with a base reference contain
420                          * an additional 20 bytes for the base sha1.
421                          */
422                         sha1write(f, entry->delta->sha1, 20);
423                         hdrlen += 20;
424                 }
425                 datalen = sha1write_compressed(f, buf, size, pack_compression_level);
426                 free(buf);
427         }
428         else {
429                 struct packed_git *p = entry->in_pack;
430                 struct pack_window *w_curs = NULL;
431                 struct revindex_entry *revidx;
432                 off_t offset;
434                 if (entry->delta) {
435                         obj_type = (allow_ofs_delta && entry->delta->offset) ?
436                                 OBJ_OFS_DELTA : OBJ_REF_DELTA;
437                         reused_delta++;
438                 }
439                 hdrlen = encode_header(obj_type, entry->size, header);
440                 sha1write(f, header, hdrlen);
441                 if (obj_type == OBJ_OFS_DELTA) {
442                         off_t ofs = entry->offset - entry->delta->offset;
443                         unsigned pos = sizeof(header) - 1;
444                         header[pos] = ofs & 127;
445                         while (ofs >>= 7)
446                                 header[--pos] = 128 | (--ofs & 127);
447                         sha1write(f, header + pos, sizeof(header) - pos);
448                         hdrlen += sizeof(header) - pos;
449                 } else if (obj_type == OBJ_REF_DELTA) {
450                         sha1write(f, entry->delta->sha1, 20);
451                         hdrlen += 20;
452                 }
454                 offset = entry->in_pack_offset;
455                 revidx = find_packed_object(p, offset);
456                 datalen = revidx[1].offset - offset;
457                 if (!pack_to_stdout && p->index_version > 1 &&
458                     check_pack_crc(p, &w_curs, offset, datalen, revidx->nr))
459                         die("bad packed object CRC for %s", sha1_to_hex(entry->sha1));
460                 offset += entry->in_pack_header_size;
461                 datalen -= entry->in_pack_header_size;
462                 if (!pack_to_stdout && p->index_version == 1 &&
463                     check_pack_inflate(p, &w_curs, offset, datalen, entry->size))
464                         die("corrupt packed object for %s", sha1_to_hex(entry->sha1));
465                 copy_pack_data(f, p, &w_curs, offset, datalen);
466                 unuse_pack(&w_curs);
467                 reused++;
468         }
469         if (entry->delta)
470                 written_delta++;
471         written++;
472         if (!pack_to_stdout)
473                 entry->crc32 = crc32_end(f);
474         return hdrlen + datalen;
477 static off_t write_one(struct sha1file *f,
478                                struct object_entry *e,
479                                off_t offset)
481         unsigned long size;
483         /* offset is non zero if object is written already. */
484         if (e->offset || e->preferred_base)
485                 return offset;
487         /* if we are deltified, write out base object first. */
488         if (e->delta)
489                 offset = write_one(f, e->delta, offset);
491         e->offset = offset;
492         size = write_object(f, e);
494         /* make sure off_t is sufficiently large not to wrap */
495         if (offset > offset + size)
496                 die("pack too large for current definition of off_t");
497         return offset + size;
500 static int open_object_dir_tmp(const char *path)
502     snprintf(tmpname, sizeof(tmpname), "%s/%s", get_object_directory(), path);
503     return mkstemp(tmpname);
506 static off_t write_pack_file(void)
508         uint32_t i;
509         struct sha1file *f;
510         off_t offset, last_obj_offset = 0;
511         struct pack_header hdr;
512         int do_progress = progress;
514         if (pack_to_stdout) {
515                 f = sha1fd(1, "<stdout>");
516                 do_progress >>= 1;
517         } else {
518                 int fd = open_object_dir_tmp("tmp_pack_XXXXXX");
519                 if (fd < 0)
520                         die("unable to create %s: %s\n", tmpname, strerror(errno));
521                 pack_tmp_name = xstrdup(tmpname);
522                 f = sha1fd(fd, pack_tmp_name);
523         }
525         if (do_progress)
526                 start_progress(&progress_state, "Writing %u objects...", "", nr_result);
528         hdr.hdr_signature = htonl(PACK_SIGNATURE);
529         hdr.hdr_version = htonl(PACK_VERSION);
530         hdr.hdr_entries = htonl(nr_result);
531         sha1write(f, &hdr, sizeof(hdr));
532         offset = sizeof(hdr);
533         if (!nr_result)
534                 goto done;
535         for (i = 0; i < nr_objects; i++) {
536                 last_obj_offset = offset;
537                 offset = write_one(f, objects + i, offset);
538                 if (do_progress)
539                         display_progress(&progress_state, written);
540         }
541         if (do_progress)
542                 stop_progress(&progress_state);
543  done:
544         if (written != nr_result)
545                 die("wrote %u objects while expecting %u", written, nr_result);
546         sha1close(f, pack_file_sha1, 1);
548         return last_obj_offset;
551 static int sha1_sort(const void *_a, const void *_b)
553         const struct object_entry *a = *(struct object_entry **)_a;
554         const struct object_entry *b = *(struct object_entry **)_b;
555         return hashcmp(a->sha1, b->sha1);
558 static uint32_t index_default_version = 1;
559 static uint32_t index_off32_limit = 0x7fffffff;
561 static void write_index_file(off_t last_obj_offset, unsigned char *sha1)
563         struct sha1file *f;
564         struct object_entry **sorted_by_sha, **list, **last;
565         uint32_t array[256];
566         uint32_t i, index_version;
567         SHA_CTX ctx;
569         int fd = open_object_dir_tmp("tmp_idx_XXXXXX");
570         if (fd < 0)
571                 die("unable to create %s: %s\n", tmpname, strerror(errno));
572         idx_tmp_name = xstrdup(tmpname);
573         f = sha1fd(fd, idx_tmp_name);
575         if (nr_result) {
576                 uint32_t j = 0;
577                 sorted_by_sha =
578                         xcalloc(nr_result, sizeof(struct object_entry *));
579                 for (i = 0; i < nr_objects; i++)
580                         if (!objects[i].preferred_base)
581                                 sorted_by_sha[j++] = objects + i;
582                 if (j != nr_result)
583                         die("listed %u objects while expecting %u", j, nr_result);
584                 qsort(sorted_by_sha, nr_result, sizeof(*sorted_by_sha), sha1_sort);
585                 list = sorted_by_sha;
586                 last = sorted_by_sha + nr_result;
587         } else
588                 sorted_by_sha = list = last = NULL;
590         /* if last object's offset is >= 2^31 we should use index V2 */
591         index_version = (last_obj_offset >> 31) ? 2 : index_default_version;
593         /* index versions 2 and above need a header */
594         if (index_version >= 2) {
595                 struct pack_idx_header hdr;
596                 hdr.idx_signature = htonl(PACK_IDX_SIGNATURE);
597                 hdr.idx_version = htonl(index_version);
598                 sha1write(f, &hdr, sizeof(hdr));
599         }
601         /*
602          * Write the first-level table (the list is sorted,
603          * but we use a 256-entry lookup to be able to avoid
604          * having to do eight extra binary search iterations).
605          */
606         for (i = 0; i < 256; i++) {
607                 struct object_entry **next = list;
608                 while (next < last) {
609                         struct object_entry *entry = *next;
610                         if (entry->sha1[0] != i)
611                                 break;
612                         next++;
613                 }
614                 array[i] = htonl(next - sorted_by_sha);
615                 list = next;
616         }
617         sha1write(f, array, 256 * 4);
619         /* Compute the SHA1 hash of sorted object names. */
620         SHA1_Init(&ctx);
622         /* Write the actual SHA1 entries. */
623         list = sorted_by_sha;
624         for (i = 0; i < nr_result; i++) {
625                 struct object_entry *entry = *list++;
626                 if (index_version < 2) {
627                         uint32_t offset = htonl(entry->offset);
628                         sha1write(f, &offset, 4);
629                 }
630                 sha1write(f, entry->sha1, 20);
631                 SHA1_Update(&ctx, entry->sha1, 20);
632         }
634         if (index_version >= 2) {
635                 unsigned int nr_large_offset = 0;
637                 /* write the crc32 table */
638                 list = sorted_by_sha;
639                 for (i = 0; i < nr_objects; i++) {
640                         struct object_entry *entry = *list++;
641                         uint32_t crc32_val = htonl(entry->crc32);
642                         sha1write(f, &crc32_val, 4);
643                 }
645                 /* write the 32-bit offset table */
646                 list = sorted_by_sha;
647                 for (i = 0; i < nr_objects; i++) {
648                         struct object_entry *entry = *list++;
649                         uint32_t offset = (entry->offset <= index_off32_limit) ?
650                                 entry->offset : (0x80000000 | nr_large_offset++);
651                         offset = htonl(offset);
652                         sha1write(f, &offset, 4);
653                 }
655                 /* write the large offset table */
656                 list = sorted_by_sha;
657                 while (nr_large_offset) {
658                         struct object_entry *entry = *list++;
659                         uint64_t offset = entry->offset;
660                         if (offset > index_off32_limit) {
661                                 uint32_t split[2];
662                                 split[0]        = htonl(offset >> 32);
663                                 split[1] = htonl(offset & 0xffffffff);
664                                 sha1write(f, split, 8);
665                                 nr_large_offset--;
666                         }
667                 }
668         }
670         sha1write(f, pack_file_sha1, 20);
671         sha1close(f, NULL, 1);
672         free(sorted_by_sha);
673         SHA1_Final(sha1, &ctx);
676 static int locate_object_entry_hash(const unsigned char *sha1)
678         int i;
679         unsigned int ui;
680         memcpy(&ui, sha1, sizeof(unsigned int));
681         i = ui % object_ix_hashsz;
682         while (0 < object_ix[i]) {
683                 if (!hashcmp(sha1, objects[object_ix[i] - 1].sha1))
684                         return i;
685                 if (++i == object_ix_hashsz)
686                         i = 0;
687         }
688         return -1 - i;
691 static struct object_entry *locate_object_entry(const unsigned char *sha1)
693         int i;
695         if (!object_ix_hashsz)
696                 return NULL;
698         i = locate_object_entry_hash(sha1);
699         if (0 <= i)
700                 return &objects[object_ix[i]-1];
701         return NULL;
704 static void rehash_objects(void)
706         uint32_t i;
707         struct object_entry *oe;
709         object_ix_hashsz = nr_objects * 3;
710         if (object_ix_hashsz < 1024)
711                 object_ix_hashsz = 1024;
712         object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
713         memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
714         for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
715                 int ix = locate_object_entry_hash(oe->sha1);
716                 if (0 <= ix)
717                         continue;
718                 ix = -1 - ix;
719                 object_ix[ix] = i + 1;
720         }
723 static unsigned name_hash(const char *name)
725         unsigned char c;
726         unsigned hash = 0;
728         if (!name)
729                 return 0;
731         /*
732          * This effectively just creates a sortable number from the
733          * last sixteen non-whitespace characters. Last characters
734          * count "most", so things that end in ".c" sort together.
735          */
736         while ((c = *name++) != 0) {
737                 if (isspace(c))
738                         continue;
739                 hash = (hash >> 2) + (c << 24);
740         }
741         return hash;
744 static void setup_delta_attr_check(struct git_attr_check *check)
746         static struct git_attr *attr_delta;
748         if (!attr_delta)
749                 attr_delta = git_attr("delta", 5);
751         check[0].attr = attr_delta;
754 static int no_try_delta(const char *path)
756         struct git_attr_check check[1];
758         setup_delta_attr_check(check);
759         if (git_checkattr(path, ARRAY_SIZE(check), check))
760                 return 0;
761         if (ATTR_FALSE(check->value))
762                 return 1;
763         return 0;
766 static int add_object_entry(const unsigned char *sha1, enum object_type type,
767                             const char *name, int exclude)
769         struct object_entry *entry;
770         struct packed_git *p, *found_pack = NULL;
771         off_t found_offset = 0;
772         int ix;
773         unsigned hash = name_hash(name);
775         ix = nr_objects ? locate_object_entry_hash(sha1) : -1;
776         if (ix >= 0) {
777                 if (exclude) {
778                         entry = objects + object_ix[ix] - 1;
779                         if (!entry->preferred_base)
780                                 nr_result--;
781                         entry->preferred_base = 1;
782                 }
783                 return 0;
784         }
786         for (p = packed_git; p; p = p->next) {
787                 off_t offset = find_pack_entry_one(sha1, p);
788                 if (offset) {
789                         if (!found_pack) {
790                                 found_offset = offset;
791                                 found_pack = p;
792                         }
793                         if (exclude)
794                                 break;
795                         if (incremental)
796                                 return 0;
797                         if (local && !p->pack_local)
798                                 return 0;
799                 }
800         }
802         if (nr_objects >= nr_alloc) {
803                 nr_alloc = (nr_alloc  + 1024) * 3 / 2;
804                 objects = xrealloc(objects, nr_alloc * sizeof(*entry));
805         }
807         entry = objects + nr_objects++;
808         memset(entry, 0, sizeof(*entry));
809         hashcpy(entry->sha1, sha1);
810         entry->hash = hash;
811         if (type)
812                 entry->type = type;
813         if (exclude)
814                 entry->preferred_base = 1;
815         else
816                 nr_result++;
817         if (found_pack) {
818                 entry->in_pack = found_pack;
819                 entry->in_pack_offset = found_offset;
820         }
822         if (object_ix_hashsz * 3 <= nr_objects * 4)
823                 rehash_objects();
824         else
825                 object_ix[-1 - ix] = nr_objects;
827         if (progress)
828                 display_progress(&progress_state, nr_objects);
830         if (name && no_try_delta(name))
831                 entry->no_try_delta = 1;
833         return 1;
836 struct pbase_tree_cache {
837         unsigned char sha1[20];
838         int ref;
839         int temporary;
840         void *tree_data;
841         unsigned long tree_size;
842 };
844 static struct pbase_tree_cache *(pbase_tree_cache[256]);
845 static int pbase_tree_cache_ix(const unsigned char *sha1)
847         return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
849 static int pbase_tree_cache_ix_incr(int ix)
851         return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
854 static struct pbase_tree {
855         struct pbase_tree *next;
856         /* This is a phony "cache" entry; we are not
857          * going to evict it nor find it through _get()
858          * mechanism -- this is for the toplevel node that
859          * would almost always change with any commit.
860          */
861         struct pbase_tree_cache pcache;
862 } *pbase_tree;
864 static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
866         struct pbase_tree_cache *ent, *nent;
867         void *data;
868         unsigned long size;
869         enum object_type type;
870         int neigh;
871         int my_ix = pbase_tree_cache_ix(sha1);
872         int available_ix = -1;
874         /* pbase-tree-cache acts as a limited hashtable.
875          * your object will be found at your index or within a few
876          * slots after that slot if it is cached.
877          */
878         for (neigh = 0; neigh < 8; neigh++) {
879                 ent = pbase_tree_cache[my_ix];
880                 if (ent && !hashcmp(ent->sha1, sha1)) {
881                         ent->ref++;
882                         return ent;
883                 }
884                 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
885                          ((0 <= available_ix) &&
886                           (!ent && pbase_tree_cache[available_ix])))
887                         available_ix = my_ix;
888                 if (!ent)
889                         break;
890                 my_ix = pbase_tree_cache_ix_incr(my_ix);
891         }
893         /* Did not find one.  Either we got a bogus request or
894          * we need to read and perhaps cache.
895          */
896         data = read_sha1_file(sha1, &type, &size);
897         if (!data)
898                 return NULL;
899         if (type != OBJ_TREE) {
900                 free(data);
901                 return NULL;
902         }
904         /* We need to either cache or return a throwaway copy */
906         if (available_ix < 0)
907                 ent = NULL;
908         else {
909                 ent = pbase_tree_cache[available_ix];
910                 my_ix = available_ix;
911         }
913         if (!ent) {
914                 nent = xmalloc(sizeof(*nent));
915                 nent->temporary = (available_ix < 0);
916         }
917         else {
918                 /* evict and reuse */
919                 free(ent->tree_data);
920                 nent = ent;
921         }
922         hashcpy(nent->sha1, sha1);
923         nent->tree_data = data;
924         nent->tree_size = size;
925         nent->ref = 1;
926         if (!nent->temporary)
927                 pbase_tree_cache[my_ix] = nent;
928         return nent;
931 static void pbase_tree_put(struct pbase_tree_cache *cache)
933         if (!cache->temporary) {
934                 cache->ref--;
935                 return;
936         }
937         free(cache->tree_data);
938         free(cache);
941 static int name_cmp_len(const char *name)
943         int i;
944         for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
945                 ;
946         return i;
949 static void add_pbase_object(struct tree_desc *tree,
950                              const char *name,
951                              int cmplen,
952                              const char *fullname)
954         struct name_entry entry;
955         int cmp;
957         while (tree_entry(tree,&entry)) {
958                 cmp = tree_entry_len(entry.path, entry.sha1) != cmplen ? 1 :
959                       memcmp(name, entry.path, cmplen);
960                 if (cmp > 0)
961                         continue;
962                 if (cmp < 0)
963                         return;
964                 if (name[cmplen] != '/') {
965                         add_object_entry(entry.sha1,
966                                          S_ISDIR(entry.mode) ? OBJ_TREE : OBJ_BLOB,
967                                          fullname, 1);
968                         return;
969                 }
970                 if (S_ISDIR(entry.mode)) {
971                         struct tree_desc sub;
972                         struct pbase_tree_cache *tree;
973                         const char *down = name+cmplen+1;
974                         int downlen = name_cmp_len(down);
976                         tree = pbase_tree_get(entry.sha1);
977                         if (!tree)
978                                 return;
979                         init_tree_desc(&sub, tree->tree_data, tree->tree_size);
981                         add_pbase_object(&sub, down, downlen, fullname);
982                         pbase_tree_put(tree);
983                 }
984         }
987 static unsigned *done_pbase_paths;
988 static int done_pbase_paths_num;
989 static int done_pbase_paths_alloc;
990 static int done_pbase_path_pos(unsigned hash)
992         int lo = 0;
993         int hi = done_pbase_paths_num;
994         while (lo < hi) {
995                 int mi = (hi + lo) / 2;
996                 if (done_pbase_paths[mi] == hash)
997                         return mi;
998                 if (done_pbase_paths[mi] < hash)
999                         hi = mi;
1000                 else
1001                         lo = mi + 1;
1002         }
1003         return -lo-1;
1006 static int check_pbase_path(unsigned hash)
1008         int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
1009         if (0 <= pos)
1010                 return 1;
1011         pos = -pos - 1;
1012         if (done_pbase_paths_alloc <= done_pbase_paths_num) {
1013                 done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
1014                 done_pbase_paths = xrealloc(done_pbase_paths,
1015                                             done_pbase_paths_alloc *
1016                                             sizeof(unsigned));
1017         }
1018         done_pbase_paths_num++;
1019         if (pos < done_pbase_paths_num)
1020                 memmove(done_pbase_paths + pos + 1,
1021                         done_pbase_paths + pos,
1022                         (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
1023         done_pbase_paths[pos] = hash;
1024         return 0;
1027 static void add_preferred_base_object(const char *name)
1029         struct pbase_tree *it;
1030         int cmplen;
1031         unsigned hash = name_hash(name);
1033         if (!num_preferred_base || check_pbase_path(hash))
1034                 return;
1036         cmplen = name_cmp_len(name);
1037         for (it = pbase_tree; it; it = it->next) {
1038                 if (cmplen == 0) {
1039                         add_object_entry(it->pcache.sha1, OBJ_TREE, NULL, 1);
1040                 }
1041                 else {
1042                         struct tree_desc tree;
1043                         init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1044                         add_pbase_object(&tree, name, cmplen, name);
1045                 }
1046         }
1049 static void add_preferred_base(unsigned char *sha1)
1051         struct pbase_tree *it;
1052         void *data;
1053         unsigned long size;
1054         unsigned char tree_sha1[20];
1056         if (window <= num_preferred_base++)
1057                 return;
1059         data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
1060         if (!data)
1061                 return;
1063         for (it = pbase_tree; it; it = it->next) {
1064                 if (!hashcmp(it->pcache.sha1, tree_sha1)) {
1065                         free(data);
1066                         return;
1067                 }
1068         }
1070         it = xcalloc(1, sizeof(*it));
1071         it->next = pbase_tree;
1072         pbase_tree = it;
1074         hashcpy(it->pcache.sha1, tree_sha1);
1075         it->pcache.tree_data = data;
1076         it->pcache.tree_size = size;
1079 static void check_object(struct object_entry *entry)
1081         if (entry->in_pack) {
1082                 struct packed_git *p = entry->in_pack;
1083                 struct pack_window *w_curs = NULL;
1084                 const unsigned char *base_ref = NULL;
1085                 struct object_entry *base_entry;
1086                 unsigned long used, used_0;
1087                 unsigned int avail;
1088                 off_t ofs;
1089                 unsigned char *buf, c;
1091                 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1093                 /*
1094                  * We want in_pack_type even if we do not reuse delta
1095                  * since non-delta representations could still be reused.
1096                  */
1097                 used = unpack_object_header_gently(buf, avail,
1098                                                    &entry->in_pack_type,
1099                                                    &entry->size);
1101                 /*
1102                  * Determine if this is a delta and if so whether we can
1103                  * reuse it or not.  Otherwise let's find out as cheaply as
1104                  * possible what the actual type and size for this object is.
1105                  */
1106                 switch (entry->in_pack_type) {
1107                 default:
1108                         /* Not a delta hence we've already got all we need. */
1109                         entry->type = entry->in_pack_type;
1110                         entry->in_pack_header_size = used;
1111                         unuse_pack(&w_curs);
1112                         return;
1113                 case OBJ_REF_DELTA:
1114                         if (!no_reuse_delta && !entry->preferred_base)
1115                                 base_ref = use_pack(p, &w_curs,
1116                                                 entry->in_pack_offset + used, NULL);
1117                         entry->in_pack_header_size = used + 20;
1118                         break;
1119                 case OBJ_OFS_DELTA:
1120                         buf = use_pack(p, &w_curs,
1121                                        entry->in_pack_offset + used, NULL);
1122                         used_0 = 0;
1123                         c = buf[used_0++];
1124                         ofs = c & 127;
1125                         while (c & 128) {
1126                                 ofs += 1;
1127                                 if (!ofs || MSB(ofs, 7))
1128                                         die("delta base offset overflow in pack for %s",
1129                                             sha1_to_hex(entry->sha1));
1130                                 c = buf[used_0++];
1131                                 ofs = (ofs << 7) + (c & 127);
1132                         }
1133                         if (ofs >= entry->in_pack_offset)
1134                                 die("delta base offset out of bound for %s",
1135                                     sha1_to_hex(entry->sha1));
1136                         ofs = entry->in_pack_offset - ofs;
1137                         if (!no_reuse_delta && !entry->preferred_base)
1138                                 base_ref = find_packed_object_name(p, ofs);
1139                         entry->in_pack_header_size = used + used_0;
1140                         break;
1141                 }
1143                 if (base_ref && (base_entry = locate_object_entry(base_ref))) {
1144                         /*
1145                          * If base_ref was set above that means we wish to
1146                          * reuse delta data, and we even found that base
1147                          * in the list of objects we want to pack. Goodie!
1148                          *
1149                          * Depth value does not matter - find_deltas() will
1150                          * never consider reused delta as the base object to
1151                          * deltify other objects against, in order to avoid
1152                          * circular deltas.
1153                          */
1154                         entry->type = entry->in_pack_type;
1155                         entry->delta = base_entry;
1156                         entry->delta_sibling = base_entry->delta_child;
1157                         base_entry->delta_child = entry;
1158                         unuse_pack(&w_curs);
1159                         return;
1160                 }
1162                 if (entry->type) {
1163                         /*
1164                          * This must be a delta and we already know what the
1165                          * final object type is.  Let's extract the actual
1166                          * object size from the delta header.
1167                          */
1168                         entry->size = get_size_from_delta(p, &w_curs,
1169                                         entry->in_pack_offset + entry->in_pack_header_size);
1170                         unuse_pack(&w_curs);
1171                         return;
1172                 }
1174                 /*
1175                  * No choice but to fall back to the recursive delta walk
1176                  * with sha1_object_info() to find about the object type
1177                  * at this point...
1178                  */
1179                 unuse_pack(&w_curs);
1180         }
1182         entry->type = sha1_object_info(entry->sha1, &entry->size);
1183         if (entry->type < 0)
1184                 die("unable to get type of object %s",
1185                     sha1_to_hex(entry->sha1));
1188 static int pack_offset_sort(const void *_a, const void *_b)
1190         const struct object_entry *a = *(struct object_entry **)_a;
1191         const struct object_entry *b = *(struct object_entry **)_b;
1193         /* avoid filesystem trashing with loose objects */
1194         if (!a->in_pack && !b->in_pack)
1195                 return hashcmp(a->sha1, b->sha1);
1197         if (a->in_pack < b->in_pack)
1198                 return -1;
1199         if (a->in_pack > b->in_pack)
1200                 return 1;
1201         return a->in_pack_offset < b->in_pack_offset ? -1 :
1202                         (a->in_pack_offset > b->in_pack_offset);
1205 static void get_object_details(void)
1207         uint32_t i;
1208         struct object_entry **sorted_by_offset;
1210         sorted_by_offset = xcalloc(nr_objects, sizeof(struct object_entry *));
1211         for (i = 0; i < nr_objects; i++)
1212                 sorted_by_offset[i] = objects + i;
1213         qsort(sorted_by_offset, nr_objects, sizeof(*sorted_by_offset), pack_offset_sort);
1215         prepare_pack_ix();
1216         for (i = 0; i < nr_objects; i++)
1217                 check_object(sorted_by_offset[i]);
1218         free(sorted_by_offset);
1221 static int type_size_sort(const void *_a, const void *_b)
1223         const struct object_entry *a = *(struct object_entry **)_a;
1224         const struct object_entry *b = *(struct object_entry **)_b;
1226         if (a->type < b->type)
1227                 return -1;
1228         if (a->type > b->type)
1229                 return 1;
1230         if (a->hash < b->hash)
1231                 return -1;
1232         if (a->hash > b->hash)
1233                 return 1;
1234         if (a->preferred_base < b->preferred_base)
1235                 return -1;
1236         if (a->preferred_base > b->preferred_base)
1237                 return 1;
1238         if (a->size < b->size)
1239                 return -1;
1240         if (a->size > b->size)
1241                 return 1;
1242         return a > b ? -1 : (a < b);  /* newest last */
1245 struct unpacked {
1246         struct object_entry *entry;
1247         void *data;
1248         struct delta_index *index;
1249 };
1251 /*
1252  * We search for deltas _backwards_ in a list sorted by type and
1253  * by size, so that we see progressively smaller and smaller files.
1254  * That's because we prefer deltas to be from the bigger file
1255  * to the smaller - deletes are potentially cheaper, but perhaps
1256  * more importantly, the bigger file is likely the more recent
1257  * one.
1258  */
1259 static int try_delta(struct unpacked *trg, struct unpacked *src,
1260                      unsigned max_depth)
1262         struct object_entry *trg_entry = trg->entry;
1263         struct object_entry *src_entry = src->entry;
1264         unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1265         enum object_type type;
1266         void *delta_buf;
1268         /* Don't bother doing diffs between different types */
1269         if (trg_entry->type != src_entry->type)
1270                 return -1;
1272         /* We do not compute delta to *create* objects we are not
1273          * going to pack.
1274          */
1275         if (trg_entry->preferred_base)
1276                 return -1;
1278         /*
1279          * We do not bother to try a delta that we discarded
1280          * on an earlier try, but only when reusing delta data.
1281          */
1282         if (!no_reuse_delta && trg_entry->in_pack &&
1283             trg_entry->in_pack == src_entry->in_pack &&
1284             trg_entry->in_pack_type != OBJ_REF_DELTA &&
1285             trg_entry->in_pack_type != OBJ_OFS_DELTA)
1286                 return 0;
1288         /* Let's not bust the allowed depth. */
1289         if (src_entry->depth >= max_depth)
1290                 return 0;
1292         /* Now some size filtering heuristics. */
1293         trg_size = trg_entry->size;
1294         max_size = trg_size/2 - 20;
1295         max_size = max_size * (max_depth - src_entry->depth) / max_depth;
1296         if (max_size == 0)
1297                 return 0;
1298         if (trg_entry->delta && trg_entry->delta_size <= max_size)
1299                 max_size = trg_entry->delta_size-1;
1300         src_size = src_entry->size;
1301         sizediff = src_size < trg_size ? trg_size - src_size : 0;
1302         if (sizediff >= max_size)
1303                 return 0;
1305         /* Load data if not already done */
1306         if (!trg->data) {
1307                 trg->data = read_sha1_file(trg_entry->sha1, &type, &sz);
1308                 if (sz != trg_size)
1309                         die("object %s inconsistent object length (%lu vs %lu)",
1310                             sha1_to_hex(trg_entry->sha1), sz, trg_size);
1311         }
1312         if (!src->data) {
1313                 src->data = read_sha1_file(src_entry->sha1, &type, &sz);
1314                 if (sz != src_size)
1315                         die("object %s inconsistent object length (%lu vs %lu)",
1316                             sha1_to_hex(src_entry->sha1), sz, src_size);
1317         }
1318         if (!src->index) {
1319                 src->index = create_delta_index(src->data, src_size);
1320                 if (!src->index)
1321                         die("out of memory");
1322         }
1324         delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1325         if (!delta_buf)
1326                 return 0;
1328         trg_entry->delta = src_entry;
1329         trg_entry->delta_size = delta_size;
1330         trg_entry->depth = src_entry->depth + 1;
1331         free(delta_buf);
1332         return 1;
1335 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
1337         struct object_entry *child = me->delta_child;
1338         unsigned int m = n;
1339         while (child) {
1340                 unsigned int c = check_delta_limit(child, n + 1);
1341                 if (m < c)
1342                         m = c;
1343                 child = child->delta_sibling;
1344         }
1345         return m;
1348 static void find_deltas(struct object_entry **list, int window, int depth)
1350         uint32_t i = nr_objects, idx = 0, processed = 0;
1351         unsigned int array_size = window * sizeof(struct unpacked);
1352         struct unpacked *array;
1353         int max_depth;
1355         if (!nr_objects)
1356                 return;
1357         array = xmalloc(array_size);
1358         memset(array, 0, array_size);
1359         if (progress)
1360                 start_progress(&progress_state, "Deltifying %u objects...", "", nr_result);
1362         do {
1363                 struct object_entry *entry = list[--i];
1364                 struct unpacked *n = array + idx;
1365                 int j;
1367                 if (!entry->preferred_base)
1368                         processed++;
1370                 if (progress)
1371                         display_progress(&progress_state, processed);
1373                 if (entry->delta)
1374                         /* This happens if we decided to reuse existing
1375                          * delta from a pack.  "!no_reuse_delta &&" is implied.
1376                          */
1377                         continue;
1379                 if (entry->size < 50)
1380                         continue;
1382                 if (entry->no_try_delta)
1383                         continue;
1385                 free_delta_index(n->index);
1386                 n->index = NULL;
1387                 free(n->data);
1388                 n->data = NULL;
1389                 n->entry = entry;
1391                 /*
1392                  * If the current object is at pack edge, take the depth the
1393                  * objects that depend on the current object into account
1394                  * otherwise they would become too deep.
1395                  */
1396                 max_depth = depth;
1397                 if (entry->delta_child) {
1398                         max_depth -= check_delta_limit(entry, 0);
1399                         if (max_depth <= 0)
1400                                 goto next;
1401                 }
1403                 j = window;
1404                 while (--j > 0) {
1405                         uint32_t other_idx = idx + j;
1406                         struct unpacked *m;
1407                         if (other_idx >= window)
1408                                 other_idx -= window;
1409                         m = array + other_idx;
1410                         if (!m->entry)
1411                                 break;
1412                         if (try_delta(n, m, max_depth) < 0)
1413                                 break;
1414                 }
1416                 /* if we made n a delta, and if n is already at max
1417                  * depth, leaving it in the window is pointless.  we
1418                  * should evict it first.
1419                  */
1420                 if (entry->delta && depth <= entry->depth)
1421                         continue;
1423                 next:
1424                 idx++;
1425                 if (idx >= window)
1426                         idx = 0;
1427         } while (i > 0);
1429         if (progress)
1430                 stop_progress(&progress_state);
1432         for (i = 0; i < window; ++i) {
1433                 free_delta_index(array[i].index);
1434                 free(array[i].data);
1435         }
1436         free(array);
1439 static void prepare_pack(int window, int depth)
1441         struct object_entry **delta_list;
1442         uint32_t i;
1444         get_object_details();
1446         if (!window || !depth)
1447                 return;
1449         delta_list = xmalloc(nr_objects * sizeof(*delta_list));
1450         for (i = 0; i < nr_objects; i++)
1451                 delta_list[i] = objects + i;
1452         qsort(delta_list, nr_objects, sizeof(*delta_list), type_size_sort);
1453         find_deltas(delta_list, window+1, depth);
1454         free(delta_list);
1457 static int git_pack_config(const char *k, const char *v)
1459         if(!strcmp(k, "pack.window")) {
1460                 window = git_config_int(k, v);
1461                 return 0;
1462         }
1463         if(!strcmp(k, "pack.depth")) {
1464                 depth = git_config_int(k, v);
1465                 return 0;
1466         }
1467         if (!strcmp(k, "pack.compression")) {
1468                 int level = git_config_int(k, v);
1469                 if (level == -1)
1470                         level = Z_DEFAULT_COMPRESSION;
1471                 else if (level < 0 || level > Z_BEST_COMPRESSION)
1472                         die("bad pack compression level %d", level);
1473                 pack_compression_level = level;
1474                 pack_compression_seen = 1;
1475                 return 0;
1476         }
1477         return git_default_config(k, v);
1480 static void read_object_list_from_stdin(void)
1482         char line[40 + 1 + PATH_MAX + 2];
1483         unsigned char sha1[20];
1485         for (;;) {
1486                 if (!fgets(line, sizeof(line), stdin)) {
1487                         if (feof(stdin))
1488                                 break;
1489                         if (!ferror(stdin))
1490                                 die("fgets returned NULL, not EOF, not error!");
1491                         if (errno != EINTR)
1492                                 die("fgets: %s", strerror(errno));
1493                         clearerr(stdin);
1494                         continue;
1495                 }
1496                 if (line[0] == '-') {
1497                         if (get_sha1_hex(line+1, sha1))
1498                                 die("expected edge sha1, got garbage:\n %s",
1499                                     line);
1500                         add_preferred_base(sha1);
1501                         continue;
1502                 }
1503                 if (get_sha1_hex(line, sha1))
1504                         die("expected sha1, got garbage:\n %s", line);
1506                 add_preferred_base_object(line+41);
1507                 add_object_entry(sha1, 0, line+41, 0);
1508         }
1511 static void show_commit(struct commit *commit)
1513         add_object_entry(commit->object.sha1, OBJ_COMMIT, NULL, 0);
1516 static void show_object(struct object_array_entry *p)
1518         add_preferred_base_object(p->name);
1519         add_object_entry(p->item->sha1, p->item->type, p->name, 0);
1522 static void show_edge(struct commit *commit)
1524         add_preferred_base(commit->object.sha1);
1527 static void get_object_list(int ac, const char **av)
1529         struct rev_info revs;
1530         char line[1000];
1531         int flags = 0;
1533         init_revisions(&revs, NULL);
1534         save_commit_buffer = 0;
1535         track_object_refs = 0;
1536         setup_revisions(ac, av, &revs, NULL);
1538         while (fgets(line, sizeof(line), stdin) != NULL) {
1539                 int len = strlen(line);
1540                 if (line[len - 1] == '\n')
1541                         line[--len] = 0;
1542                 if (!len)
1543                         break;
1544                 if (*line == '-') {
1545                         if (!strcmp(line, "--not")) {
1546                                 flags ^= UNINTERESTING;
1547                                 continue;
1548                         }
1549                         die("not a rev '%s'", line);
1550                 }
1551                 if (handle_revision_arg(line, &revs, flags, 1))
1552                         die("bad revision '%s'", line);
1553         }
1555         prepare_revision_walk(&revs);
1556         mark_edges_uninteresting(revs.commits, &revs, show_edge);
1557         traverse_commit_list(&revs, show_commit, show_object);
1560 static int adjust_perm(const char *path, mode_t mode)
1562         if (chmod(path, mode))
1563                 return -1;
1564         return adjust_shared_perm(path);
1567 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
1569         int use_internal_rev_list = 0;
1570         int thin = 0;
1571         uint32_t i;
1572         off_t last_obj_offset;
1573         const char *base_name = NULL;
1574         const char **rp_av;
1575         int rp_ac_alloc = 64;
1576         int rp_ac;
1578         rp_av = xcalloc(rp_ac_alloc, sizeof(*rp_av));
1580         rp_av[0] = "pack-objects";
1581         rp_av[1] = "--objects"; /* --thin will make it --objects-edge */
1582         rp_ac = 2;
1584         git_config(git_pack_config);
1585         if (!pack_compression_seen && core_compression_seen)
1586                 pack_compression_level = core_compression_level;
1588         progress = isatty(2);
1589         for (i = 1; i < argc; i++) {
1590                 const char *arg = argv[i];
1592                 if (*arg != '-')
1593                         break;
1595                 if (!strcmp("--non-empty", arg)) {
1596                         non_empty = 1;
1597                         continue;
1598                 }
1599                 if (!strcmp("--local", arg)) {
1600                         local = 1;
1601                         continue;
1602                 }
1603                 if (!strcmp("--incremental", arg)) {
1604                         incremental = 1;
1605                         continue;
1606                 }
1607                 if (!prefixcmp(arg, "--compression=")) {
1608                         char *end;
1609                         int level = strtoul(arg+14, &end, 0);
1610                         if (!arg[14] || *end)
1611                                 usage(pack_usage);
1612                         if (level == -1)
1613                                 level = Z_DEFAULT_COMPRESSION;
1614                         else if (level < 0 || level > Z_BEST_COMPRESSION)
1615                                 die("bad pack compression level %d", level);
1616                         pack_compression_level = level;
1617                         continue;
1618                 }
1619                 if (!prefixcmp(arg, "--window=")) {
1620                         char *end;
1621                         window = strtoul(arg+9, &end, 0);
1622                         if (!arg[9] || *end)
1623                                 usage(pack_usage);
1624                         continue;
1625                 }
1626                 if (!prefixcmp(arg, "--depth=")) {
1627                         char *end;
1628                         depth = strtoul(arg+8, &end, 0);
1629                         if (!arg[8] || *end)
1630                                 usage(pack_usage);
1631                         continue;
1632                 }
1633                 if (!strcmp("--progress", arg)) {
1634                         progress = 1;
1635                         continue;
1636                 }
1637                 if (!strcmp("--all-progress", arg)) {
1638                         progress = 2;
1639                         continue;
1640                 }
1641                 if (!strcmp("-q", arg)) {
1642                         progress = 0;
1643                         continue;
1644                 }
1645                 if (!strcmp("--no-reuse-delta", arg)) {
1646                         no_reuse_delta = 1;
1647                         continue;
1648                 }
1649                 if (!strcmp("--no-reuse-object", arg)) {
1650                         no_reuse_object = no_reuse_delta = 1;
1651                         continue;
1652                 }
1653                 if (!strcmp("--delta-base-offset", arg)) {
1654                         allow_ofs_delta = 1;
1655                         continue;
1656                 }
1657                 if (!strcmp("--stdout", arg)) {
1658                         pack_to_stdout = 1;
1659                         continue;
1660                 }
1661                 if (!strcmp("--revs", arg)) {
1662                         use_internal_rev_list = 1;
1663                         continue;
1664                 }
1665                 if (!strcmp("--unpacked", arg) ||
1666                     !prefixcmp(arg, "--unpacked=") ||
1667                     !strcmp("--reflog", arg) ||
1668                     !strcmp("--all", arg)) {
1669                         use_internal_rev_list = 1;
1670                         if (rp_ac >= rp_ac_alloc - 1) {
1671                                 rp_ac_alloc = alloc_nr(rp_ac_alloc);
1672                                 rp_av = xrealloc(rp_av,
1673                                                  rp_ac_alloc * sizeof(*rp_av));
1674                         }
1675                         rp_av[rp_ac++] = arg;
1676                         continue;
1677                 }
1678                 if (!strcmp("--thin", arg)) {
1679                         use_internal_rev_list = 1;
1680                         thin = 1;
1681                         rp_av[1] = "--objects-edge";
1682                         continue;
1683                 }
1684                 if (!prefixcmp(arg, "--index-version=")) {
1685                         char *c;
1686                         index_default_version = strtoul(arg + 16, &c, 10);
1687                         if (index_default_version > 2)
1688                                 die("bad %s", arg);
1689                         if (*c == ',')
1690                                 index_off32_limit = strtoul(c+1, &c, 0);
1691                         if (*c || index_off32_limit & 0x80000000)
1692                                 die("bad %s", arg);
1693                         continue;
1694                 }
1695                 usage(pack_usage);
1696         }
1698         /* Traditionally "pack-objects [options] base extra" failed;
1699          * we would however want to take refs parameter that would
1700          * have been given to upstream rev-list ourselves, which means
1701          * we somehow want to say what the base name is.  So the
1702          * syntax would be:
1703          *
1704          * pack-objects [options] base <refs...>
1705          *
1706          * in other words, we would treat the first non-option as the
1707          * base_name and send everything else to the internal revision
1708          * walker.
1709          */
1711         if (!pack_to_stdout)
1712                 base_name = argv[i++];
1714         if (pack_to_stdout != !base_name)
1715                 usage(pack_usage);
1717         if (!pack_to_stdout && thin)
1718                 die("--thin cannot be used to build an indexable pack.");
1720         prepare_packed_git();
1722         if (progress)
1723                 start_progress(&progress_state, "Generating pack...",
1724                                "Counting objects: ", 0);
1725         if (!use_internal_rev_list)
1726                 read_object_list_from_stdin();
1727         else {
1728                 rp_av[rp_ac] = NULL;
1729                 get_object_list(rp_ac, rp_av);
1730         }
1731         if (progress) {
1732                 stop_progress(&progress_state);
1733                 fprintf(stderr, "Done counting %u objects.\n", nr_objects);
1734         }
1736         if (non_empty && !nr_result)
1737                 return 0;
1738         if (progress && (nr_objects != nr_result))
1739                 fprintf(stderr, "Result has %u objects.\n", nr_result);
1740         if (nr_result)
1741                 prepare_pack(window, depth);
1742         last_obj_offset = write_pack_file();
1743         if (!pack_to_stdout) {
1744                 unsigned char object_list_sha1[20];
1745                 mode_t mode = umask(0);
1747                 umask(mode);
1748                 mode = 0444 & ~mode;
1750                 write_index_file(last_obj_offset, object_list_sha1);
1751                 snprintf(tmpname, sizeof(tmpname), "%s-%s.pack",
1752                          base_name, sha1_to_hex(object_list_sha1));
1753                 if (adjust_perm(pack_tmp_name, mode))
1754                         die("unable to make temporary pack file readable: %s",
1755                             strerror(errno));
1756                 if (rename(pack_tmp_name, tmpname))
1757                         die("unable to rename temporary pack file: %s",
1758                             strerror(errno));
1759                 snprintf(tmpname, sizeof(tmpname), "%s-%s.idx",
1760                          base_name, sha1_to_hex(object_list_sha1));
1761                 if (adjust_perm(idx_tmp_name, mode))
1762                         die("unable to make temporary index file readable: %s",
1763                             strerror(errno));
1764                 if (rename(idx_tmp_name, tmpname))
1765                         die("unable to rename temporary index file: %s",
1766                             strerror(errno));
1767                 puts(sha1_to_hex(object_list_sha1));
1768         }
1769         if (progress)
1770                 fprintf(stderr, "Total %u (delta %u), reused %u (delta %u)\n",
1771                         written, written_delta, reused, reused_delta);
1772         return 0;