Code

upload-pack.c: <sys/poll.h> includes <ctype.h> on OpenBSD 3.8
[git.git] / pack-objects.c
1 #include "cache.h"
2 #include "object.h"
3 #include "blob.h"
4 #include "commit.h"
5 #include "tag.h"
6 #include "tree.h"
7 #include "delta.h"
8 #include "pack.h"
9 #include "csum-file.h"
10 #include "tree-walk.h"
11 #include <sys/time.h>
12 #include <signal.h>
14 static const char pack_usage[] = "git-pack-objects [-q] [--no-reuse-delta] [--non-empty] [--local] [--incremental] [--window=N] [--depth=N] {--stdout | base-name} < object-list";
16 struct object_entry {
17         unsigned char sha1[20];
18         unsigned long size;     /* uncompressed size */
19         unsigned long offset;   /* offset into the final pack file;
20                                  * nonzero if already written.
21                                  */
22         unsigned int depth;     /* delta depth */
23         unsigned int delta_limit;       /* base adjustment for in-pack delta */
24         unsigned int hash;      /* name hint hash */
25         enum object_type type;
26         enum object_type in_pack_type;  /* could be delta */
27         unsigned long delta_size;       /* delta data size (uncompressed) */
28         struct object_entry *delta;     /* delta base object */
29         struct packed_git *in_pack;     /* already in pack */
30         unsigned int in_pack_offset;
31         struct object_entry *delta_child; /* delitified objects who bases me */
32         struct object_entry *delta_sibling; /* other deltified objects who
33                                              * uses the same base as me
34                                              */
35         int preferred_base;     /* we do not pack this, but is encouraged to
36                                  * be used as the base objectto delta huge
37                                  * objects against.
38                                  */
39 };
41 /*
42  * Objects we are going to pack are colected in objects array (dynamically
43  * expanded).  nr_objects & nr_alloc controls this array.  They are stored
44  * in the order we see -- typically rev-list --objects order that gives us
45  * nice "minimum seek" order.
46  *
47  * sorted-by-sha ans sorted-by-type are arrays of pointers that point at
48  * elements in the objects array.  The former is used to build the pack
49  * index (lists object names in the ascending order to help offset lookup),
50  * and the latter is used to group similar things together by try_delta()
51  * heuristics.
52  */
54 static unsigned char object_list_sha1[20];
55 static int non_empty = 0;
56 static int no_reuse_delta = 0;
57 static int local = 0;
58 static int incremental = 0;
59 static struct object_entry **sorted_by_sha, **sorted_by_type;
60 static struct object_entry *objects = NULL;
61 static int nr_objects = 0, nr_alloc = 0, nr_result = 0;
62 static const char *base_name;
63 static unsigned char pack_file_sha1[20];
64 static int progress = 1;
65 static volatile sig_atomic_t progress_update = 0;
67 /*
68  * The object names in objects array are hashed with this hashtable,
69  * to help looking up the entry by object name.  Binary search from
70  * sorted_by_sha is also possible but this was easier to code and faster.
71  * This hashtable is built after all the objects are seen.
72  */
73 static int *object_ix = NULL;
74 static int object_ix_hashsz = 0;
76 /*
77  * Pack index for existing packs give us easy access to the offsets into
78  * corresponding pack file where each object's data starts, but the entries
79  * do not store the size of the compressed representation (uncompressed
80  * size is easily available by examining the pack entry header).  We build
81  * a hashtable of existing packs (pack_revindex), and keep reverse index
82  * here -- pack index file is sorted by object name mapping to offset; this
83  * pack_revindex[].revindex array is an ordered list of offsets, so if you
84  * know the offset of an object, next offset is where its packed
85  * representation ends.
86  */
87 struct pack_revindex {
88         struct packed_git *p;
89         unsigned long *revindex;
90 } *pack_revindex = NULL;
91 static int pack_revindex_hashsz = 0;
93 /*
94  * stats
95  */
96 static int written = 0;
97 static int written_delta = 0;
98 static int reused = 0;
99 static int reused_delta = 0;
101 static int pack_revindex_ix(struct packed_git *p)
103         unsigned long ui = (unsigned long)p;
104         int i;
106         ui = ui ^ (ui >> 16); /* defeat structure alignment */
107         i = (int)(ui % pack_revindex_hashsz);
108         while (pack_revindex[i].p) {
109                 if (pack_revindex[i].p == p)
110                         return i;
111                 if (++i == pack_revindex_hashsz)
112                         i = 0;
113         }
114         return -1 - i;
117 static void prepare_pack_ix(void)
119         int num;
120         struct packed_git *p;
121         for (num = 0, p = packed_git; p; p = p->next)
122                 num++;
123         if (!num)
124                 return;
125         pack_revindex_hashsz = num * 11;
126         pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
127         for (p = packed_git; p; p = p->next) {
128                 num = pack_revindex_ix(p);
129                 num = - 1 - num;
130                 pack_revindex[num].p = p;
131         }
132         /* revindex elements are lazily initialized */
135 static int cmp_offset(const void *a_, const void *b_)
137         unsigned long a = *(unsigned long *) a_;
138         unsigned long b = *(unsigned long *) b_;
139         if (a < b)
140                 return -1;
141         else if (a == b)
142                 return 0;
143         else
144                 return 1;
147 /*
148  * Ordered list of offsets of objects in the pack.
149  */
150 static void prepare_pack_revindex(struct pack_revindex *rix)
152         struct packed_git *p = rix->p;
153         int num_ent = num_packed_objects(p);
154         int i;
155         void *index = p->index_base + 256;
157         rix->revindex = xmalloc(sizeof(unsigned long) * (num_ent + 1));
158         for (i = 0; i < num_ent; i++) {
159                 unsigned int hl = *((unsigned int *)((char *) index + 24*i));
160                 rix->revindex[i] = ntohl(hl);
161         }
162         /* This knows the pack format -- the 20-byte trailer
163          * follows immediately after the last object data.
164          */
165         rix->revindex[num_ent] = p->pack_size - 20;
166         qsort(rix->revindex, num_ent, sizeof(unsigned long), cmp_offset);
169 static unsigned long find_packed_object_size(struct packed_git *p,
170                                              unsigned long ofs)
172         int num;
173         int lo, hi;
174         struct pack_revindex *rix;
175         unsigned long *revindex;
176         num = pack_revindex_ix(p);
177         if (num < 0)
178                 die("internal error: pack revindex uninitialized");
179         rix = &pack_revindex[num];
180         if (!rix->revindex)
181                 prepare_pack_revindex(rix);
182         revindex = rix->revindex;
183         lo = 0;
184         hi = num_packed_objects(p) + 1;
185         do {
186                 int mi = (lo + hi) / 2;
187                 if (revindex[mi] == ofs) {
188                         return revindex[mi+1] - ofs;
189                 }
190                 else if (ofs < revindex[mi])
191                         hi = mi;
192                 else
193                         lo = mi + 1;
194         } while (lo < hi);
195         die("internal error: pack revindex corrupt");
198 static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
200         unsigned long othersize, delta_size;
201         char type[10];
202         void *otherbuf = read_sha1_file(entry->delta->sha1, type, &othersize);
203         void *delta_buf;
205         if (!otherbuf)
206                 die("unable to read %s", sha1_to_hex(entry->delta->sha1));
207         delta_buf = diff_delta(otherbuf, othersize,
208                                buf, size, &delta_size, 0);
209         if (!delta_buf || delta_size != entry->delta_size)
210                 die("delta size changed");
211         free(buf);
212         free(otherbuf);
213         return delta_buf;
216 /*
217  * The per-object header is a pretty dense thing, which is
218  *  - first byte: low four bits are "size", then three bits of "type",
219  *    and the high bit is "size continues".
220  *  - each byte afterwards: low seven bits are size continuation,
221  *    with the high bit being "size continues"
222  */
223 static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
225         int n = 1;
226         unsigned char c;
228         if (type < OBJ_COMMIT || type > OBJ_DELTA)
229                 die("bad type %d", type);
231         c = (type << 4) | (size & 15);
232         size >>= 4;
233         while (size) {
234                 *hdr++ = c | 0x80;
235                 c = size & 0x7f;
236                 size >>= 7;
237                 n++;
238         }
239         *hdr = c;
240         return n;
243 static unsigned long write_object(struct sha1file *f,
244                                   struct object_entry *entry)
246         unsigned long size;
247         char type[10];
248         void *buf;
249         unsigned char header[10];
250         unsigned hdrlen, datalen;
251         enum object_type obj_type;
252         int to_reuse = 0;
254         if (entry->preferred_base)
255                 return 0;
257         obj_type = entry->type;
258         if (! entry->in_pack)
259                 to_reuse = 0;   /* can't reuse what we don't have */
260         else if (obj_type == OBJ_DELTA)
261                 to_reuse = 1;   /* check_object() decided it for us */
262         else if (obj_type != entry->in_pack_type)
263                 to_reuse = 0;   /* pack has delta which is unusable */
264         else if (entry->delta)
265                 to_reuse = 0;   /* we want to pack afresh */
266         else
267                 to_reuse = 1;   /* we have it in-pack undeltified,
268                                  * and we do not need to deltify it.
269                                  */
271         if (! to_reuse) {
272                 buf = read_sha1_file(entry->sha1, type, &size);
273                 if (!buf)
274                         die("unable to read %s", sha1_to_hex(entry->sha1));
275                 if (size != entry->size)
276                         die("object %s size inconsistency (%lu vs %lu)",
277                             sha1_to_hex(entry->sha1), size, entry->size);
278                 if (entry->delta) {
279                         buf = delta_against(buf, size, entry);
280                         size = entry->delta_size;
281                         obj_type = OBJ_DELTA;
282                 }
283                 /*
284                  * The object header is a byte of 'type' followed by zero or
285                  * more bytes of length.  For deltas, the 20 bytes of delta
286                  * sha1 follows that.
287                  */
288                 hdrlen = encode_header(obj_type, size, header);
289                 sha1write(f, header, hdrlen);
291                 if (entry->delta) {
292                         sha1write(f, entry->delta, 20);
293                         hdrlen += 20;
294                 }
295                 datalen = sha1write_compressed(f, buf, size);
296                 free(buf);
297         }
298         else {
299                 struct packed_git *p = entry->in_pack;
300                 use_packed_git(p);
302                 datalen = find_packed_object_size(p, entry->in_pack_offset);
303                 buf = (char *) p->pack_base + entry->in_pack_offset;
304                 sha1write(f, buf, datalen);
305                 unuse_packed_git(p);
306                 hdrlen = 0; /* not really */
307                 if (obj_type == OBJ_DELTA)
308                         reused_delta++;
309                 reused++;
310         }
311         if (obj_type == OBJ_DELTA)
312                 written_delta++;
313         written++;
314         return hdrlen + datalen;
317 static unsigned long write_one(struct sha1file *f,
318                                struct object_entry *e,
319                                unsigned long offset)
321         if (e->offset)
322                 /* offset starts from header size and cannot be zero
323                  * if it is written already.
324                  */
325                 return offset;
326         e->offset = offset;
327         offset += write_object(f, e);
328         /* if we are deltified, write out its base object. */
329         if (e->delta)
330                 offset = write_one(f, e->delta, offset);
331         return offset;
334 static void write_pack_file(void)
336         int i;
337         struct sha1file *f;
338         unsigned long offset;
339         struct pack_header hdr;
340         unsigned last_percent = 999;
341         int do_progress = 0;
343         if (!base_name)
344                 f = sha1fd(1, "<stdout>");
345         else {
346                 f = sha1create("%s-%s.%s", base_name,
347                                sha1_to_hex(object_list_sha1), "pack");
348                 do_progress = progress;
349         }
350         if (do_progress)
351                 fprintf(stderr, "Writing %d objects.\n", nr_result);
353         hdr.hdr_signature = htonl(PACK_SIGNATURE);
354         hdr.hdr_version = htonl(PACK_VERSION);
355         hdr.hdr_entries = htonl(nr_result);
356         sha1write(f, &hdr, sizeof(hdr));
357         offset = sizeof(hdr);
358         if (!nr_result)
359                 goto done;
360         for (i = 0; i < nr_objects; i++) {
361                 offset = write_one(f, objects + i, offset);
362                 if (do_progress) {
363                         unsigned percent = written * 100 / nr_result;
364                         if (progress_update || percent != last_percent) {
365                                 fprintf(stderr, "%4u%% (%u/%u) done\r",
366                                         percent, written, nr_result);
367                                 progress_update = 0;
368                                 last_percent = percent;
369                         }
370                 }
371         }
372         if (do_progress)
373                 fputc('\n', stderr);
374  done:
375         sha1close(f, pack_file_sha1, 1);
378 static void write_index_file(void)
380         int i;
381         struct sha1file *f = sha1create("%s-%s.%s", base_name,
382                                         sha1_to_hex(object_list_sha1), "idx");
383         struct object_entry **list = sorted_by_sha;
384         struct object_entry **last = list + nr_result;
385         unsigned int array[256];
387         /*
388          * Write the first-level table (the list is sorted,
389          * but we use a 256-entry lookup to be able to avoid
390          * having to do eight extra binary search iterations).
391          */
392         for (i = 0; i < 256; i++) {
393                 struct object_entry **next = list;
394                 while (next < last) {
395                         struct object_entry *entry = *next;
396                         if (entry->sha1[0] != i)
397                                 break;
398                         next++;
399                 }
400                 array[i] = htonl(next - sorted_by_sha);
401                 list = next;
402         }
403         sha1write(f, array, 256 * sizeof(int));
405         /*
406          * Write the actual SHA1 entries..
407          */
408         list = sorted_by_sha;
409         for (i = 0; i < nr_result; i++) {
410                 struct object_entry *entry = *list++;
411                 unsigned int offset = htonl(entry->offset);
412                 sha1write(f, &offset, 4);
413                 sha1write(f, entry->sha1, 20);
414         }
415         sha1write(f, pack_file_sha1, 20);
416         sha1close(f, NULL, 1);
419 static int locate_object_entry_hash(const unsigned char *sha1)
421         int i;
422         unsigned int ui;
423         memcpy(&ui, sha1, sizeof(unsigned int));
424         i = ui % object_ix_hashsz;
425         while (0 < object_ix[i]) {
426                 if (!memcmp(sha1, objects[object_ix[i]-1].sha1, 20))
427                         return i;
428                 if (++i == object_ix_hashsz)
429                         i = 0;
430         }
431         return -1 - i;
434 static struct object_entry *locate_object_entry(const unsigned char *sha1)
436         int i;
438         if (!object_ix_hashsz)
439                 return NULL;
441         i = locate_object_entry_hash(sha1);
442         if (0 <= i)
443                 return &objects[object_ix[i]-1];
444         return NULL;
447 static void rehash_objects(void)
449         int i;
450         struct object_entry *oe;
452         object_ix_hashsz = nr_objects * 3;
453         if (object_ix_hashsz < 1024)
454                 object_ix_hashsz = 1024;
455         object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
456         memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
457         for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
458                 int ix = locate_object_entry_hash(oe->sha1);
459                 if (0 <= ix)
460                         continue;
461                 ix = -1 - ix;
462                 object_ix[ix] = i + 1;
463         }
466 static unsigned name_hash(const char *name)
468         unsigned char c;
469         unsigned hash = 0;
471         /*
472          * This effectively just creates a sortable number from the
473          * last sixteen non-whitespace characters. Last characters
474          * count "most", so things that end in ".c" sort together.
475          */
476         while ((c = *name++) != 0) {
477                 if (isspace(c))
478                         continue;
479                 hash = (hash >> 2) + (c << 24);
480         }
481         return hash;
484 static int add_object_entry(const unsigned char *sha1, unsigned hash, int exclude)
486         unsigned int idx = nr_objects;
487         struct object_entry *entry;
488         struct packed_git *p;
489         unsigned int found_offset = 0;
490         struct packed_git *found_pack = NULL;
491         int ix, status = 0;
493         if (!exclude) {
494                 for (p = packed_git; p; p = p->next) {
495                         struct pack_entry e;
496                         if (find_pack_entry_one(sha1, &e, p)) {
497                                 if (incremental)
498                                         return 0;
499                                 if (local && !p->pack_local)
500                                         return 0;
501                                 if (!found_pack) {
502                                         found_offset = e.offset;
503                                         found_pack = e.p;
504                                 }
505                         }
506                 }
507         }
508         if ((entry = locate_object_entry(sha1)) != NULL)
509                 goto already_added;
511         if (idx >= nr_alloc) {
512                 unsigned int needed = (idx + 1024) * 3 / 2;
513                 objects = xrealloc(objects, needed * sizeof(*entry));
514                 nr_alloc = needed;
515         }
516         entry = objects + idx;
517         nr_objects = idx + 1;
518         memset(entry, 0, sizeof(*entry));
519         memcpy(entry->sha1, sha1, 20);
520         entry->hash = hash;
522         if (object_ix_hashsz * 3 <= nr_objects * 4)
523                 rehash_objects();
524         else {
525                 ix = locate_object_entry_hash(entry->sha1);
526                 if (0 <= ix)
527                         die("internal error in object hashing.");
528                 object_ix[-1 - ix] = idx + 1;
529         }
530         status = 1;
532  already_added:
533         if (progress_update) {
534                 fprintf(stderr, "Counting objects...%d\r", nr_objects);
535                 progress_update = 0;
536         }
537         if (exclude)
538                 entry->preferred_base = 1;
539         else {
540                 if (found_pack) {
541                         entry->in_pack = found_pack;
542                         entry->in_pack_offset = found_offset;
543                 }
544         }
545         return status;
548 struct pbase_tree_cache {
549         unsigned char sha1[20];
550         int ref;
551         int temporary;
552         void *tree_data;
553         unsigned long tree_size;
554 };
556 static struct pbase_tree_cache *(pbase_tree_cache[256]);
557 static int pbase_tree_cache_ix(const unsigned char *sha1)
559         return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
561 static int pbase_tree_cache_ix_incr(int ix)
563         return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
566 static struct pbase_tree {
567         struct pbase_tree *next;
568         /* This is a phony "cache" entry; we are not
569          * going to evict it nor find it through _get()
570          * mechanism -- this is for the toplevel node that
571          * would almost always change with any commit.
572          */
573         struct pbase_tree_cache pcache;
574 } *pbase_tree;
576 static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
578         struct pbase_tree_cache *ent, *nent;
579         void *data;
580         unsigned long size;
581         char type[20];
582         int neigh;
583         int my_ix = pbase_tree_cache_ix(sha1);
584         int available_ix = -1;
586         /* pbase-tree-cache acts as a limited hashtable.
587          * your object will be found at your index or within a few
588          * slots after that slot if it is cached.
589          */
590         for (neigh = 0; neigh < 8; neigh++) {
591                 ent = pbase_tree_cache[my_ix];
592                 if (ent && !memcmp(ent->sha1, sha1, 20)) {
593                         ent->ref++;
594                         return ent;
595                 }
596                 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
597                          ((0 <= available_ix) &&
598                           (!ent && pbase_tree_cache[available_ix])))
599                         available_ix = my_ix;
600                 if (!ent)
601                         break;
602                 my_ix = pbase_tree_cache_ix_incr(my_ix);
603         }
605         /* Did not find one.  Either we got a bogus request or
606          * we need to read and perhaps cache.
607          */
608         data = read_sha1_file(sha1, type, &size);
609         if (!data)
610                 return NULL;
611         if (strcmp(type, tree_type)) {
612                 free(data);
613                 return NULL;
614         }
616         /* We need to either cache or return a throwaway copy */
618         if (available_ix < 0)
619                 ent = NULL;
620         else {
621                 ent = pbase_tree_cache[available_ix];
622                 my_ix = available_ix;
623         }
625         if (!ent) {
626                 nent = xmalloc(sizeof(*nent));
627                 nent->temporary = (available_ix < 0);
628         }
629         else {
630                 /* evict and reuse */
631                 free(ent->tree_data);
632                 nent = ent;
633         }
634         memcpy(nent->sha1, sha1, 20);
635         nent->tree_data = data;
636         nent->tree_size = size;
637         nent->ref = 1;
638         if (!nent->temporary)
639                 pbase_tree_cache[my_ix] = nent;
640         return nent;
643 static void pbase_tree_put(struct pbase_tree_cache *cache)
645         if (!cache->temporary) {
646                 cache->ref--;
647                 return;
648         }
649         free(cache->tree_data);
650         free(cache);
653 static int name_cmp_len(const char *name)
655         int i;
656         for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
657                 ;
658         return i;
661 static void add_pbase_object(struct tree_desc *tree,
662                              const char *name,
663                              int cmplen,
664                              const char *fullname)
666         struct name_entry entry;
668         while (tree_entry(tree,&entry)) {
669                 unsigned long size;
670                 char type[20];
672                 if (entry.pathlen != cmplen ||
673                     memcmp(entry.path, name, cmplen) ||
674                     !has_sha1_file(entry.sha1) ||
675                     sha1_object_info(entry.sha1, type, &size))
676                         continue;
677                 if (name[cmplen] != '/') {
678                         unsigned hash = name_hash(fullname);
679                         add_object_entry(entry.sha1, hash, 1);
680                         return;
681                 }
682                 if (!strcmp(type, tree_type)) {
683                         struct tree_desc sub;
684                         struct pbase_tree_cache *tree;
685                         const char *down = name+cmplen+1;
686                         int downlen = name_cmp_len(down);
688                         tree = pbase_tree_get(entry.sha1);
689                         if (!tree)
690                                 return;
691                         sub.buf = tree->tree_data;
692                         sub.size = tree->tree_size;
694                         add_pbase_object(&sub, down, downlen, fullname);
695                         pbase_tree_put(tree);
696                 }
697         }
700 static unsigned *done_pbase_paths;
701 static int done_pbase_paths_num;
702 static int done_pbase_paths_alloc;
703 static int done_pbase_path_pos(unsigned hash)
705         int lo = 0;
706         int hi = done_pbase_paths_num;
707         while (lo < hi) {
708                 int mi = (hi + lo) / 2;
709                 if (done_pbase_paths[mi] == hash)
710                         return mi;
711                 if (done_pbase_paths[mi] < hash)
712                         hi = mi;
713                 else
714                         lo = mi + 1;
715         }
716         return -lo-1;
719 static int check_pbase_path(unsigned hash)
721         int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
722         if (0 <= pos)
723                 return 1;
724         pos = -pos - 1;
725         if (done_pbase_paths_alloc <= done_pbase_paths_num) {
726                 done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
727                 done_pbase_paths = xrealloc(done_pbase_paths,
728                                             done_pbase_paths_alloc *
729                                             sizeof(unsigned));
730         }
731         done_pbase_paths_num++;
732         if (pos < done_pbase_paths_num)
733                 memmove(done_pbase_paths + pos + 1,
734                         done_pbase_paths + pos,
735                         (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
736         done_pbase_paths[pos] = hash;
737         return 0;
740 static void add_preferred_base_object(char *name, unsigned hash)
742         struct pbase_tree *it;
743         int cmplen = name_cmp_len(name);
745         if (check_pbase_path(hash))
746                 return;
748         for (it = pbase_tree; it; it = it->next) {
749                 if (cmplen == 0) {
750                         hash = name_hash("");
751                         add_object_entry(it->pcache.sha1, hash, 1);
752                 }
753                 else {
754                         struct tree_desc tree;
755                         tree.buf = it->pcache.tree_data;
756                         tree.size = it->pcache.tree_size;
757                         add_pbase_object(&tree, name, cmplen, name);
758                 }
759         }
762 static void add_preferred_base(unsigned char *sha1)
764         struct pbase_tree *it;
765         void *data;
766         unsigned long size;
767         unsigned char tree_sha1[20];
769         data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
770         if (!data)
771                 return;
773         for (it = pbase_tree; it; it = it->next) {
774                 if (!memcmp(it->pcache.sha1, tree_sha1, 20)) {
775                         free(data);
776                         return;
777                 }
778         }
780         it = xcalloc(1, sizeof(*it));
781         it->next = pbase_tree;
782         pbase_tree = it;
784         memcpy(it->pcache.sha1, tree_sha1, 20);
785         it->pcache.tree_data = data;
786         it->pcache.tree_size = size;
789 static void check_object(struct object_entry *entry)
791         char type[20];
793         if (entry->in_pack && !entry->preferred_base) {
794                 unsigned char base[20];
795                 unsigned long size;
796                 struct object_entry *base_entry;
798                 /* We want in_pack_type even if we do not reuse delta.
799                  * There is no point not reusing non-delta representations.
800                  */
801                 check_reuse_pack_delta(entry->in_pack,
802                                        entry->in_pack_offset,
803                                        base, &size,
804                                        &entry->in_pack_type);
806                 /* Check if it is delta, and the base is also an object
807                  * we are going to pack.  If so we will reuse the existing
808                  * delta.
809                  */
810                 if (!no_reuse_delta &&
811                     entry->in_pack_type == OBJ_DELTA &&
812                     (base_entry = locate_object_entry(base)) &&
813                     (!base_entry->preferred_base)) {
815                         /* Depth value does not matter - find_deltas()
816                          * will never consider reused delta as the
817                          * base object to deltify other objects
818                          * against, in order to avoid circular deltas.
819                          */
821                         /* uncompressed size of the delta data */
822                         entry->size = entry->delta_size = size;
823                         entry->delta = base_entry;
824                         entry->type = OBJ_DELTA;
826                         entry->delta_sibling = base_entry->delta_child;
827                         base_entry->delta_child = entry;
829                         return;
830                 }
831                 /* Otherwise we would do the usual */
832         }
834         if (sha1_object_info(entry->sha1, type, &entry->size))
835                 die("unable to get type of object %s",
836                     sha1_to_hex(entry->sha1));
838         if (!strcmp(type, commit_type)) {
839                 entry->type = OBJ_COMMIT;
840         } else if (!strcmp(type, tree_type)) {
841                 entry->type = OBJ_TREE;
842         } else if (!strcmp(type, blob_type)) {
843                 entry->type = OBJ_BLOB;
844         } else if (!strcmp(type, tag_type)) {
845                 entry->type = OBJ_TAG;
846         } else
847                 die("unable to pack object %s of type %s",
848                     sha1_to_hex(entry->sha1), type);
851 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
853         struct object_entry *child = me->delta_child;
854         unsigned int m = n;
855         while (child) {
856                 unsigned int c = check_delta_limit(child, n + 1);
857                 if (m < c)
858                         m = c;
859                 child = child->delta_sibling;
860         }
861         return m;
864 static void get_object_details(void)
866         int i;
867         struct object_entry *entry;
869         prepare_pack_ix();
870         for (i = 0, entry = objects; i < nr_objects; i++, entry++)
871                 check_object(entry);
873         if (nr_objects == nr_result) {
874                 /*
875                  * Depth of objects that depend on the entry -- this
876                  * is subtracted from depth-max to break too deep
877                  * delta chain because of delta data reusing.
878                  * However, we loosen this restriction when we know we
879                  * are creating a thin pack -- it will have to be
880                  * expanded on the other end anyway, so do not
881                  * artificially cut the delta chain and let it go as
882                  * deep as it wants.
883                  */
884                 for (i = 0, entry = objects; i < nr_objects; i++, entry++)
885                         if (!entry->delta && entry->delta_child)
886                                 entry->delta_limit =
887                                         check_delta_limit(entry, 1);
888         }
891 typedef int (*entry_sort_t)(const struct object_entry *, const struct object_entry *);
893 static entry_sort_t current_sort;
895 static int sort_comparator(const void *_a, const void *_b)
897         struct object_entry *a = *(struct object_entry **)_a;
898         struct object_entry *b = *(struct object_entry **)_b;
899         return current_sort(a,b);
902 static struct object_entry **create_sorted_list(entry_sort_t sort)
904         struct object_entry **list = xmalloc(nr_objects * sizeof(struct object_entry *));
905         int i;
907         for (i = 0; i < nr_objects; i++)
908                 list[i] = objects + i;
909         current_sort = sort;
910         qsort(list, nr_objects, sizeof(struct object_entry *), sort_comparator);
911         return list;
914 static int sha1_sort(const struct object_entry *a, const struct object_entry *b)
916         return memcmp(a->sha1, b->sha1, 20);
919 static struct object_entry **create_final_object_list(void)
921         struct object_entry **list;
922         int i, j;
924         for (i = nr_result = 0; i < nr_objects; i++)
925                 if (!objects[i].preferred_base)
926                         nr_result++;
927         list = xmalloc(nr_result * sizeof(struct object_entry *));
928         for (i = j = 0; i < nr_objects; i++) {
929                 if (!objects[i].preferred_base)
930                         list[j++] = objects + i;
931         }
932         current_sort = sha1_sort;
933         qsort(list, nr_result, sizeof(struct object_entry *), sort_comparator);
934         return list;
937 static int type_size_sort(const struct object_entry *a, const struct object_entry *b)
939         if (a->type < b->type)
940                 return -1;
941         if (a->type > b->type)
942                 return 1;
943         if (a->hash < b->hash)
944                 return -1;
945         if (a->hash > b->hash)
946                 return 1;
947         if (a->preferred_base < b->preferred_base)
948                 return -1;
949         if (a->preferred_base > b->preferred_base)
950                 return 1;
951         if (a->size < b->size)
952                 return -1;
953         if (a->size > b->size)
954                 return 1;
955         return a < b ? -1 : (a > b);
958 struct unpacked {
959         struct object_entry *entry;
960         void *data;
961         struct delta_index *index;
962 };
964 /*
965  * We search for deltas _backwards_ in a list sorted by type and
966  * by size, so that we see progressively smaller and smaller files.
967  * That's because we prefer deltas to be from the bigger file
968  * to the smaller - deletes are potentially cheaper, but perhaps
969  * more importantly, the bigger file is likely the more recent
970  * one.
971  */
972 static int try_delta(struct unpacked *trg, struct unpacked *src,
973                      struct delta_index *src_index, unsigned max_depth)
975         struct object_entry *trg_entry = trg->entry;
976         struct object_entry *src_entry = src->entry;
977         unsigned long size, src_size, delta_size, sizediff, max_size;
978         void *delta_buf;
980         /* Don't bother doing diffs between different types */
981         if (trg_entry->type != src_entry->type)
982                 return -1;
984         /* We do not compute delta to *create* objects we are not
985          * going to pack.
986          */
987         if (trg_entry->preferred_base)
988                 return -1;
990         /*
991          * We do not bother to try a delta that we discarded
992          * on an earlier try, but only when reusing delta data.
993          */
994         if (!no_reuse_delta && trg_entry->in_pack &&
995             trg_entry->in_pack == src_entry->in_pack)
996                 return 0;
998         /*
999          * If the current object is at pack edge, take the depth the
1000          * objects that depend on the current object into account --
1001          * otherwise they would become too deep.
1002          */
1003         if (trg_entry->delta_child) {
1004                 if (max_depth <= trg_entry->delta_limit)
1005                         return 0;
1006                 max_depth -= trg_entry->delta_limit;
1007         }
1008         if (src_entry->depth >= max_depth)
1009                 return 0;
1011         /* Now some size filtering heuristics. */
1012         size = trg_entry->size;
1013         max_size = size/2 - 20;
1014         max_size = max_size * (max_depth - src_entry->depth) / max_depth;
1015         if (max_size == 0)
1016                 return 0;
1017         if (trg_entry->delta && trg_entry->delta_size <= max_size)
1018                 max_size = trg_entry->delta_size-1;
1019         src_size = src_entry->size;
1020         sizediff = src_size < size ? size - src_size : 0;
1021         if (sizediff >= max_size)
1022                 return 0;
1024         delta_buf = create_delta(src_index, trg->data, size, &delta_size, max_size);
1025         if (!delta_buf)
1026                 return 0;
1028         trg_entry->delta = src_entry;
1029         trg_entry->delta_size = delta_size;
1030         trg_entry->depth = src_entry->depth + 1;
1031         free(delta_buf);
1032         return 1;
1035 static void progress_interval(int signum)
1037         progress_update = 1;
1040 static void find_deltas(struct object_entry **list, int window, int depth)
1042         int i, idx;
1043         unsigned int array_size = window * sizeof(struct unpacked);
1044         struct unpacked *array = xmalloc(array_size);
1045         unsigned processed = 0;
1046         unsigned last_percent = 999;
1048         memset(array, 0, array_size);
1049         i = nr_objects;
1050         idx = 0;
1051         if (progress)
1052                 fprintf(stderr, "Deltifying %d objects.\n", nr_result);
1054         while (--i >= 0) {
1055                 struct object_entry *entry = list[i];
1056                 struct unpacked *n = array + idx;
1057                 unsigned long size;
1058                 char type[10];
1059                 int j;
1061                 if (!entry->preferred_base)
1062                         processed++;
1064                 if (progress) {
1065                         unsigned percent = processed * 100 / nr_result;
1066                         if (percent != last_percent || progress_update) {
1067                                 fprintf(stderr, "%4u%% (%u/%u) done\r",
1068                                         percent, processed, nr_result);
1069                                 progress_update = 0;
1070                                 last_percent = percent;
1071                         }
1072                 }
1074                 if (entry->delta)
1075                         /* This happens if we decided to reuse existing
1076                          * delta from a pack.  "!no_reuse_delta &&" is implied.
1077                          */
1078                         continue;
1080                 if (entry->size < 50)
1081                         continue;
1082                 free_delta_index(n->index);
1083                 n->index = NULL;
1084                 free(n->data);
1085                 n->entry = entry;
1086                 n->data = read_sha1_file(entry->sha1, type, &size);
1087                 if (size != entry->size)
1088                         die("object %s inconsistent object length (%lu vs %lu)",
1089                             sha1_to_hex(entry->sha1), size, entry->size);
1091                 j = window;
1092                 while (--j > 0) {
1093                         unsigned int other_idx = idx + j;
1094                         struct unpacked *m;
1095                         if (other_idx >= window)
1096                                 other_idx -= window;
1097                         m = array + other_idx;
1098                         if (!m->entry)
1099                                 break;
1100                         if (try_delta(n, m, m->index, depth) < 0)
1101                                 break;
1102                 }
1103                 /* if we made n a delta, and if n is already at max
1104                  * depth, leaving it in the window is pointless.  we
1105                  * should evict it first.
1106                  */
1107                 if (entry->delta && depth <= entry->depth)
1108                         continue;
1110                 n->index = create_delta_index(n->data, size);
1111                 if (!n->index)
1112                         die("out of memory");
1114                 idx++;
1115                 if (idx >= window)
1116                         idx = 0;
1117         }
1119         if (progress)
1120                 fputc('\n', stderr);
1122         for (i = 0; i < window; ++i) {
1123                 free_delta_index(array[i].index);
1124                 free(array[i].data);
1125         }
1126         free(array);
1129 static void prepare_pack(int window, int depth)
1131         get_object_details();
1132         sorted_by_type = create_sorted_list(type_size_sort);
1133         if (window && depth)
1134                 find_deltas(sorted_by_type, window+1, depth);
1137 static int reuse_cached_pack(unsigned char *sha1, int pack_to_stdout)
1139         static const char cache[] = "pack-cache/pack-%s.%s";
1140         char *cached_pack, *cached_idx;
1141         int ifd, ofd, ifd_ix = -1;
1143         cached_pack = git_path(cache, sha1_to_hex(sha1), "pack");
1144         ifd = open(cached_pack, O_RDONLY);
1145         if (ifd < 0)
1146                 return 0;
1148         if (!pack_to_stdout) {
1149                 cached_idx = git_path(cache, sha1_to_hex(sha1), "idx");
1150                 ifd_ix = open(cached_idx, O_RDONLY);
1151                 if (ifd_ix < 0) {
1152                         close(ifd);
1153                         return 0;
1154                 }
1155         }
1157         if (progress)
1158                 fprintf(stderr, "Reusing %d objects pack %s\n", nr_objects,
1159                         sha1_to_hex(sha1));
1161         if (pack_to_stdout) {
1162                 if (copy_fd(ifd, 1))
1163                         exit(1);
1164                 close(ifd);
1165         }
1166         else {
1167                 char name[PATH_MAX];
1168                 snprintf(name, sizeof(name),
1169                          "%s-%s.%s", base_name, sha1_to_hex(sha1), "pack");
1170                 ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1171                 if (ofd < 0)
1172                         die("unable to open %s (%s)", name, strerror(errno));
1173                 if (copy_fd(ifd, ofd))
1174                         exit(1);
1175                 close(ifd);
1177                 snprintf(name, sizeof(name),
1178                          "%s-%s.%s", base_name, sha1_to_hex(sha1), "idx");
1179                 ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1180                 if (ofd < 0)
1181                         die("unable to open %s (%s)", name, strerror(errno));
1182                 if (copy_fd(ifd_ix, ofd))
1183                         exit(1);
1184                 close(ifd_ix);
1185                 puts(sha1_to_hex(sha1));
1186         }
1188         return 1;
1191 static void setup_progress_signal(void)
1193         struct sigaction sa;
1194         struct itimerval v;
1196         memset(&sa, 0, sizeof(sa));
1197         sa.sa_handler = progress_interval;
1198         sigemptyset(&sa.sa_mask);
1199         sa.sa_flags = SA_RESTART;
1200         sigaction(SIGALRM, &sa, NULL);
1202         v.it_interval.tv_sec = 1;
1203         v.it_interval.tv_usec = 0;
1204         v.it_value = v.it_interval;
1205         setitimer(ITIMER_REAL, &v, NULL);
1208 int main(int argc, char **argv)
1210         SHA_CTX ctx;
1211         char line[40 + 1 + PATH_MAX + 2];
1212         int window = 10, depth = 10, pack_to_stdout = 0;
1213         struct object_entry **list;
1214         int num_preferred_base = 0;
1215         int i;
1217         setup_git_directory();
1219         progress = isatty(2);
1220         for (i = 1; i < argc; i++) {
1221                 const char *arg = argv[i];
1223                 if (*arg == '-') {
1224                         if (!strcmp("--non-empty", arg)) {
1225                                 non_empty = 1;
1226                                 continue;
1227                         }
1228                         if (!strcmp("--local", arg)) {
1229                                 local = 1;
1230                                 continue;
1231                         }
1232                         if (!strcmp("--progress", arg)) {
1233                                 progress = 1;
1234                                 continue;
1235                         }
1236                         if (!strcmp("--incremental", arg)) {
1237                                 incremental = 1;
1238                                 continue;
1239                         }
1240                         if (!strncmp("--window=", arg, 9)) {
1241                                 char *end;
1242                                 window = strtoul(arg+9, &end, 0);
1243                                 if (!arg[9] || *end)
1244                                         usage(pack_usage);
1245                                 continue;
1246                         }
1247                         if (!strncmp("--depth=", arg, 8)) {
1248                                 char *end;
1249                                 depth = strtoul(arg+8, &end, 0);
1250                                 if (!arg[8] || *end)
1251                                         usage(pack_usage);
1252                                 continue;
1253                         }
1254                         if (!strcmp("--progress", arg)) {
1255                                 progress = 1;
1256                                 continue;
1257                         }
1258                         if (!strcmp("-q", arg)) {
1259                                 progress = 0;
1260                                 continue;
1261                         }
1262                         if (!strcmp("--no-reuse-delta", arg)) {
1263                                 no_reuse_delta = 1;
1264                                 continue;
1265                         }
1266                         if (!strcmp("--stdout", arg)) {
1267                                 pack_to_stdout = 1;
1268                                 continue;
1269                         }
1270                         usage(pack_usage);
1271                 }
1272                 if (base_name)
1273                         usage(pack_usage);
1274                 base_name = arg;
1275         }
1277         if (pack_to_stdout != !base_name)
1278                 usage(pack_usage);
1280         prepare_packed_git();
1282         if (progress) {
1283                 fprintf(stderr, "Generating pack...\n");
1284                 setup_progress_signal();
1285         }
1287         for (;;) {
1288                 unsigned char sha1[20];
1289                 unsigned hash;
1291                 if (!fgets(line, sizeof(line), stdin)) {
1292                         if (feof(stdin))
1293                                 break;
1294                         if (!ferror(stdin))
1295                                 die("fgets returned NULL, not EOF, not error!");
1296                         if (errno != EINTR)
1297                                 die("fgets: %s", strerror(errno));
1298                         clearerr(stdin);
1299                         continue;
1300                 }
1302                 if (line[0] == '-') {
1303                         if (get_sha1_hex(line+1, sha1))
1304                                 die("expected edge sha1, got garbage:\n %s",
1305                                     line+1);
1306                         if (num_preferred_base++ < window)
1307                                 add_preferred_base(sha1);
1308                         continue;
1309                 }
1310                 if (get_sha1_hex(line, sha1))
1311                         die("expected sha1, got garbage:\n %s", line);
1312                 hash = name_hash(line+41);
1313                 add_preferred_base_object(line+41, hash);
1314                 add_object_entry(sha1, hash, 0);
1315         }
1316         if (progress)
1317                 fprintf(stderr, "Done counting %d objects.\n", nr_objects);
1318         sorted_by_sha = create_final_object_list();
1319         if (non_empty && !nr_result)
1320                 return 0;
1322         SHA1_Init(&ctx);
1323         list = sorted_by_sha;
1324         for (i = 0; i < nr_result; i++) {
1325                 struct object_entry *entry = *list++;
1326                 SHA1_Update(&ctx, entry->sha1, 20);
1327         }
1328         SHA1_Final(object_list_sha1, &ctx);
1329         if (progress && (nr_objects != nr_result))
1330                 fprintf(stderr, "Result has %d objects.\n", nr_result);
1332         if (reuse_cached_pack(object_list_sha1, pack_to_stdout))
1333                 ;
1334         else {
1335                 if (nr_result)
1336                         prepare_pack(window, depth);
1337                 if (progress && pack_to_stdout) {
1338                         /* the other end usually displays progress itself */
1339                         struct itimerval v = {{0,},};
1340                         setitimer(ITIMER_REAL, &v, NULL);
1341                         signal(SIGALRM, SIG_IGN );
1342                         progress_update = 0;
1343                 }
1344                 write_pack_file();
1345                 if (!pack_to_stdout) {
1346                         write_index_file();
1347                         puts(sha1_to_hex(object_list_sha1));
1348                 }
1349         }
1350         if (progress)
1351                 fprintf(stderr, "Total %d, written %d (delta %d), reused %d (delta %d)\n",
1352                         nr_result, written, written_delta, reused, reused_delta);
1353         return 0;