Create/delete branch ref logs.
[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>
13
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";
15
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 };
40
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  */
53
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;
66
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;
75
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;
92
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;
100
101 static int pack_revindex_ix(struct packed_git *p)
102 {
103         unsigned long ui = (unsigned long)p;
104         int i;
105
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;
115 }
116
117 static void prepare_pack_ix(void)
118 {
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 */
133 }
134
135 static int cmp_offset(const void *a_, const void *b_)
136 {
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;
145 }
146
147 /*
148  * Ordered list of offsets of objects in the pack.
149  */
150 static void prepare_pack_revindex(struct pack_revindex *rix)
151 {
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;
156
157         rix->revindex = xmalloc(sizeof(unsigned long) * (num_ent + 1));
158         for (i = 0; i < num_ent; i++) {
159                 unsigned int hl = *((unsigned int *)(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);
167 }
168
169 static unsigned long find_packed_object_size(struct packed_git *p,
170                                              unsigned long ofs)
171 {
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");
196 }
197
198 static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
199 {
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;
204
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;
214 }
215
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)
224 {
225         int n = 1;
226         unsigned char c;
227
228         if (type < OBJ_COMMIT || type > OBJ_DELTA)
229                 die("bad type %d", type);
230
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;
241 }
242
243 static unsigned long write_object(struct sha1file *f,
244                                   struct object_entry *entry)
245 {
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;
253
254         if (entry->preferred_base)
255                 return 0;
256
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                                  */
270
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);
290
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);
301
302                 datalen = find_packed_object_size(p, entry->in_pack_offset);
303                 buf = 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;
315 }
316
317 static unsigned long write_one(struct sha1file *f,
318                                struct object_entry *e,
319                                unsigned long offset)
320 {
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;
332 }
333
334 static void write_pack_file(void)
335 {
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;
342
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);
352
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);
376 }
377
378 static void write_index_file(void)
379 {
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];
386
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));
404
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);
417 }
418
419 static int locate_object_entry_hash(const unsigned char *sha1)
420 {
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;
432 }
433
434 static struct object_entry *locate_object_entry(const unsigned char *sha1)
435 {
436         int i;
437
438         if (!object_ix_hashsz)
439                 return NULL;
440
441         i = locate_object_entry_hash(sha1);
442         if (0 <= i)
443                 return &objects[object_ix[i]-1];
444         return NULL;
445 }
446
447 static void rehash_objects(void)
448 {
449         int i;
450         struct object_entry *oe;
451
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         }
464 }
465
466 struct name_path {
467         struct name_path *up;
468         const char *elem;
469         int len;
470 };
471
472 #define DIRBITS 12
473
474 static unsigned name_hash(struct name_path *path, const char *name)
475 {
476         struct name_path *p = path;
477         const char *n = name + strlen(name);
478         unsigned hash = 0, name_hash = 0, name_done = 0;
479
480         if (n != name && n[-1] == '\n')
481                 n--;
482         while (name <= --n) {
483                 unsigned char c = *n;
484                 if (c == '/' && !name_done) {
485                         name_hash = hash;
486                         name_done = 1;
487                         hash = 0;
488                 }
489                 hash = hash * 11 + c;
490         }
491         if (!name_done) {
492                 name_hash = hash;
493                 hash = 0;
494         }
495         for (p = path; p; p = p->up) {
496                 hash = hash * 11 + '/';
497                 n = p->elem + p->len;
498                 while (p->elem <= --n) {
499                         unsigned char c = *n;
500                         hash = hash * 11 + c;
501                 }
502         }
503         /*
504          * Make sure "Makefile" and "t/Makefile" are hashed separately
505          * but close enough.
506          */
507         hash = (name_hash<<DIRBITS) | (hash & ((1U<<DIRBITS )-1));
508         return hash;
509 }
510
511 static int add_object_entry(const unsigned char *sha1, unsigned hash, int exclude)
512 {
513         unsigned int idx = nr_objects;
514         struct object_entry *entry;
515         struct packed_git *p;
516         unsigned int found_offset = 0;
517         struct packed_git *found_pack = NULL;
518         int ix, status = 0;
519
520         if (!exclude) {
521                 for (p = packed_git; p; p = p->next) {
522                         struct pack_entry e;
523                         if (find_pack_entry_one(sha1, &e, p)) {
524                                 if (incremental)
525                                         return 0;
526                                 if (local && !p->pack_local)
527                                         return 0;
528                                 if (!found_pack) {
529                                         found_offset = e.offset;
530                                         found_pack = e.p;
531                                 }
532                         }
533                 }
534         }
535         if ((entry = locate_object_entry(sha1)) != NULL)
536                 goto already_added;
537
538         if (idx >= nr_alloc) {
539                 unsigned int needed = (idx + 1024) * 3 / 2;
540                 objects = xrealloc(objects, needed * sizeof(*entry));
541                 nr_alloc = needed;
542         }
543         entry = objects + idx;
544         nr_objects = idx + 1;
545         memset(entry, 0, sizeof(*entry));
546         memcpy(entry->sha1, sha1, 20);
547         entry->hash = hash;
548
549         if (object_ix_hashsz * 3 <= nr_objects * 4)
550                 rehash_objects();
551         else {
552                 ix = locate_object_entry_hash(entry->sha1);
553                 if (0 <= ix)
554                         die("internal error in object hashing.");
555                 object_ix[-1 - ix] = idx + 1;
556         }
557         status = 1;
558
559  already_added:
560         if (progress_update) {
561                 fprintf(stderr, "Counting objects...%d\r", nr_objects);
562                 progress_update = 0;
563         }
564         if (exclude)
565                 entry->preferred_base = 1;
566         else {
567                 if (found_pack) {
568                         entry->in_pack = found_pack;
569                         entry->in_pack_offset = found_offset;
570                 }
571         }
572         return status;
573 }
574
575 struct pbase_tree_cache {
576         unsigned char sha1[20];
577         int ref;
578         int temporary;
579         void *tree_data;
580         unsigned long tree_size;
581 };
582
583 static struct pbase_tree_cache *(pbase_tree_cache[256]);
584 static int pbase_tree_cache_ix(const unsigned char *sha1)
585 {
586         return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
587 }
588 static int pbase_tree_cache_ix_incr(int ix)
589 {
590         return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
591 }
592
593 static struct pbase_tree {
594         struct pbase_tree *next;
595         /* This is a phony "cache" entry; we are not
596          * going to evict it nor find it through _get()
597          * mechanism -- this is for the toplevel node that
598          * would almost always change with any commit.
599          */
600         struct pbase_tree_cache pcache;
601 } *pbase_tree;
602
603 static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
604 {
605         struct pbase_tree_cache *ent, *nent;
606         void *data;
607         unsigned long size;
608         char type[20];
609         int neigh;
610         int my_ix = pbase_tree_cache_ix(sha1);
611         int available_ix = -1;
612
613         /* pbase-tree-cache acts as a limited hashtable.
614          * your object will be found at your index or within a few
615          * slots after that slot if it is cached.
616          */
617         for (neigh = 0; neigh < 8; neigh++) {
618                 ent = pbase_tree_cache[my_ix];
619                 if (ent && !memcmp(ent->sha1, sha1, 20)) {
620                         ent->ref++;
621                         return ent;
622                 }
623                 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
624                          ((0 <= available_ix) &&
625                           (!ent && pbase_tree_cache[available_ix])))
626                         available_ix = my_ix;
627                 if (!ent)
628                         break;
629                 my_ix = pbase_tree_cache_ix_incr(my_ix);
630         }
631
632         /* Did not find one.  Either we got a bogus request or
633          * we need to read and perhaps cache.
634          */
635         data = read_sha1_file(sha1, type, &size);
636         if (!data)
637                 return NULL;
638         if (strcmp(type, tree_type)) {
639                 free(data);
640                 return NULL;
641         }
642
643         /* We need to either cache or return a throwaway copy */
644
645         if (available_ix < 0)
646                 ent = NULL;
647         else {
648                 ent = pbase_tree_cache[available_ix];
649                 my_ix = available_ix;
650         }
651
652         if (!ent) {
653                 nent = xmalloc(sizeof(*nent));
654                 nent->temporary = (available_ix < 0);
655         }
656         else {
657                 /* evict and reuse */
658                 free(ent->tree_data);
659                 nent = ent;
660         }
661         memcpy(nent->sha1, sha1, 20);
662         nent->tree_data = data;
663         nent->tree_size = size;
664         nent->ref = 1;
665         if (!nent->temporary)
666                 pbase_tree_cache[my_ix] = nent;
667         return nent;
668 }
669
670 static void pbase_tree_put(struct pbase_tree_cache *cache)
671 {
672         if (!cache->temporary) {
673                 cache->ref--;
674                 return;
675         }
676         free(cache->tree_data);
677         free(cache);
678 }
679
680 static int name_cmp_len(const char *name)
681 {
682         int i;
683         for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
684                 ;
685         return i;
686 }
687
688 static void add_pbase_object(struct tree_desc *tree,
689                              struct name_path *up,
690                              const char *name,
691                              int cmplen)
692 {
693         while (tree->size) {
694                 const unsigned char *sha1;
695                 const char *entry_name;
696                 int entry_len;
697                 unsigned mode;
698                 unsigned long size;
699                 char type[20];
700
701                 sha1 = tree_entry_extract(tree, &entry_name, &mode);
702                 update_tree_entry(tree);
703                 entry_len = strlen(entry_name);
704                 if (entry_len != cmplen ||
705                     memcmp(entry_name, name, cmplen) ||
706                     !has_sha1_file(sha1) ||
707                     sha1_object_info(sha1, type, &size))
708                         continue;
709                 if (name[cmplen] != '/') {
710                         unsigned hash = name_hash(up, name);
711                         add_object_entry(sha1, hash, 1);
712                         return;
713                 }
714                 if (!strcmp(type, tree_type)) {
715                         struct tree_desc sub;
716                         struct name_path me;
717                         struct pbase_tree_cache *tree;
718                         const char *down = name+cmplen+1;
719                         int downlen = name_cmp_len(down);
720
721                         tree = pbase_tree_get(sha1);
722                         if (!tree)
723                                 return;
724                         sub.buf = tree->tree_data;
725                         sub.size = tree->tree_size;
726
727                         me.up = up;
728                         me.elem = entry_name;
729                         me.len = entry_len;
730                         add_pbase_object(&sub, &me, down, downlen);
731                         pbase_tree_put(tree);
732                 }
733         }
734 }
735
736 static unsigned *done_pbase_paths;
737 static int done_pbase_paths_num;
738 static int done_pbase_paths_alloc;
739 static int done_pbase_path_pos(unsigned hash)
740 {
741         int lo = 0;
742         int hi = done_pbase_paths_num;
743         while (lo < hi) {
744                 int mi = (hi + lo) / 2;
745                 if (done_pbase_paths[mi] == hash)
746                         return mi;
747                 if (done_pbase_paths[mi] < hash)
748                         hi = mi;
749                 else
750                         lo = mi + 1;
751         }
752         return -lo-1;
753 }
754
755 static int check_pbase_path(unsigned hash)
756 {
757         int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
758         if (0 <= pos)
759                 return 1;
760         pos = -pos - 1;
761         if (done_pbase_paths_alloc <= done_pbase_paths_num) {
762                 done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
763                 done_pbase_paths = xrealloc(done_pbase_paths,
764                                             done_pbase_paths_alloc *
765                                             sizeof(unsigned));
766         }
767         done_pbase_paths_num++;
768         if (pos < done_pbase_paths_num)
769                 memmove(done_pbase_paths + pos + 1,
770                         done_pbase_paths + pos,
771                         (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
772         done_pbase_paths[pos] = hash;
773         return 0;
774 }
775
776 static void add_preferred_base_object(char *name, unsigned hash)
777 {
778         struct pbase_tree *it;
779         int cmplen = name_cmp_len(name);
780
781         if (check_pbase_path(hash))
782                 return;
783
784         for (it = pbase_tree; it; it = it->next) {
785                 if (cmplen == 0) {
786                         hash = name_hash(NULL, "");
787                         add_object_entry(it->pcache.sha1, hash, 1);
788                 }
789                 else {
790                         struct tree_desc tree;
791                         tree.buf = it->pcache.tree_data;
792                         tree.size = it->pcache.tree_size;
793                         add_pbase_object(&tree, NULL, name, cmplen);
794                 }
795         }
796 }
797
798 static void add_preferred_base(unsigned char *sha1)
799 {
800         struct pbase_tree *it;
801         void *data;
802         unsigned long size;
803         unsigned char tree_sha1[20];
804
805         data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
806         if (!data)
807                 return;
808
809         for (it = pbase_tree; it; it = it->next) {
810                 if (!memcmp(it->pcache.sha1, tree_sha1, 20)) {
811                         free(data);
812                         return;
813                 }
814         }
815
816         it = xcalloc(1, sizeof(*it));
817         it->next = pbase_tree;
818         pbase_tree = it;
819
820         memcpy(it->pcache.sha1, tree_sha1, 20);
821         it->pcache.tree_data = data;
822         it->pcache.tree_size = size;
823 }
824
825 static void check_object(struct object_entry *entry)
826 {
827         char type[20];
828
829         if (entry->in_pack && !entry->preferred_base) {
830                 unsigned char base[20];
831                 unsigned long size;
832                 struct object_entry *base_entry;
833
834                 /* We want in_pack_type even if we do not reuse delta.
835                  * There is no point not reusing non-delta representations.
836                  */
837                 check_reuse_pack_delta(entry->in_pack,
838                                        entry->in_pack_offset,
839                                        base, &size,
840                                        &entry->in_pack_type);
841
842                 /* Check if it is delta, and the base is also an object
843                  * we are going to pack.  If so we will reuse the existing
844                  * delta.
845                  */
846                 if (!no_reuse_delta &&
847                     entry->in_pack_type == OBJ_DELTA &&
848                     (base_entry = locate_object_entry(base)) &&
849                     (!base_entry->preferred_base)) {
850
851                         /* Depth value does not matter - find_deltas()
852                          * will never consider reused delta as the
853                          * base object to deltify other objects
854                          * against, in order to avoid circular deltas.
855                          */
856
857                         /* uncompressed size of the delta data */
858                         entry->size = entry->delta_size = size;
859                         entry->delta = base_entry;
860                         entry->type = OBJ_DELTA;
861
862                         entry->delta_sibling = base_entry->delta_child;
863                         base_entry->delta_child = entry;
864
865                         return;
866                 }
867                 /* Otherwise we would do the usual */
868         }
869
870         if (sha1_object_info(entry->sha1, type, &entry->size))
871                 die("unable to get type of object %s",
872                     sha1_to_hex(entry->sha1));
873
874         if (!strcmp(type, commit_type)) {
875                 entry->type = OBJ_COMMIT;
876         } else if (!strcmp(type, tree_type)) {
877                 entry->type = OBJ_TREE;
878         } else if (!strcmp(type, blob_type)) {
879                 entry->type = OBJ_BLOB;
880         } else if (!strcmp(type, tag_type)) {
881                 entry->type = OBJ_TAG;
882         } else
883                 die("unable to pack object %s of type %s",
884                     sha1_to_hex(entry->sha1), type);
885 }
886
887 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
888 {
889         struct object_entry *child = me->delta_child;
890         unsigned int m = n;
891         while (child) {
892                 unsigned int c = check_delta_limit(child, n + 1);
893                 if (m < c)
894                         m = c;
895                 child = child->delta_sibling;
896         }
897         return m;
898 }
899
900 static void get_object_details(void)
901 {
902         int i;
903         struct object_entry *entry;
904
905         prepare_pack_ix();
906         for (i = 0, entry = objects; i < nr_objects; i++, entry++)
907                 check_object(entry);
908
909         if (nr_objects == nr_result) {
910                 /*
911                  * Depth of objects that depend on the entry -- this
912                  * is subtracted from depth-max to break too deep
913                  * delta chain because of delta data reusing.
914                  * However, we loosen this restriction when we know we
915                  * are creating a thin pack -- it will have to be
916                  * expanded on the other end anyway, so do not
917                  * artificially cut the delta chain and let it go as
918                  * deep as it wants.
919                  */
920                 for (i = 0, entry = objects; i < nr_objects; i++, entry++)
921                         if (!entry->delta && entry->delta_child)
922                                 entry->delta_limit =
923                                         check_delta_limit(entry, 1);
924         }
925 }
926
927 typedef int (*entry_sort_t)(const struct object_entry *, const struct object_entry *);
928
929 static entry_sort_t current_sort;
930
931 static int sort_comparator(const void *_a, const void *_b)
932 {
933         struct object_entry *a = *(struct object_entry **)_a;
934         struct object_entry *b = *(struct object_entry **)_b;
935         return current_sort(a,b);
936 }
937
938 static struct object_entry **create_sorted_list(entry_sort_t sort)
939 {
940         struct object_entry **list = xmalloc(nr_objects * sizeof(struct object_entry *));
941         int i;
942
943         for (i = 0; i < nr_objects; i++)
944                 list[i] = objects + i;
945         current_sort = sort;
946         qsort(list, nr_objects, sizeof(struct object_entry *), sort_comparator);
947         return list;
948 }
949
950 static int sha1_sort(const struct object_entry *a, const struct object_entry *b)
951 {
952         return memcmp(a->sha1, b->sha1, 20);
953 }
954
955 static struct object_entry **create_final_object_list(void)
956 {
957         struct object_entry **list;
958         int i, j;
959
960         for (i = nr_result = 0; i < nr_objects; i++)
961                 if (!objects[i].preferred_base)
962                         nr_result++;
963         list = xmalloc(nr_result * sizeof(struct object_entry *));
964         for (i = j = 0; i < nr_objects; i++) {
965                 if (!objects[i].preferred_base)
966                         list[j++] = objects + i;
967         }
968         current_sort = sha1_sort;
969         qsort(list, nr_result, sizeof(struct object_entry *), sort_comparator);
970         return list;
971 }
972
973 static int type_size_sort(const struct object_entry *a, const struct object_entry *b)
974 {
975         if (a->type < b->type)
976                 return -1;
977         if (a->type > b->type)
978                 return 1;
979         if (a->hash < b->hash)
980                 return -1;
981         if (a->hash > b->hash)
982                 return 1;
983         if (a->preferred_base < b->preferred_base)
984                 return -1;
985         if (a->preferred_base > b->preferred_base)
986                 return 1;
987         if (a->size < b->size)
988                 return -1;
989         if (a->size > b->size)
990                 return 1;
991         return a < b ? -1 : (a > b);
992 }
993
994 struct unpacked {
995         struct object_entry *entry;
996         void *data;
997         struct delta_index *index;
998 };
999
1000 /*
1001  * We search for deltas _backwards_ in a list sorted by type and
1002  * by size, so that we see progressively smaller and smaller files.
1003  * That's because we prefer deltas to be from the bigger file
1004  * to the smaller - deletes are potentially cheaper, but perhaps
1005  * more importantly, the bigger file is likely the more recent
1006  * one.
1007  */
1008 static int try_delta(struct unpacked *trg, struct unpacked *src,
1009                      struct delta_index *src_index, unsigned max_depth)
1010 {
1011         struct object_entry *trg_entry = trg->entry;
1012         struct object_entry *src_entry = src->entry;
1013         unsigned long size, src_size, delta_size, sizediff, max_size;
1014         void *delta_buf;
1015
1016         /* Don't bother doing diffs between different types */
1017         if (trg_entry->type != src_entry->type)
1018                 return -1;
1019
1020         /* We do not compute delta to *create* objects we are not
1021          * going to pack.
1022          */
1023         if (trg_entry->preferred_base)
1024                 return -1;
1025
1026         /*
1027          * If the current object is at pack edge, take the depth the
1028          * objects that depend on the current object into account --
1029          * otherwise they would become too deep.
1030          */
1031         if (trg_entry->delta_child) {
1032                 if (max_depth <= trg_entry->delta_limit)
1033                         return 0;
1034                 max_depth -= trg_entry->delta_limit;
1035         }
1036         if (src_entry->depth >= max_depth)
1037                 return 0;
1038
1039         /* Now some size filtering heuristics. */
1040         size = trg_entry->size;
1041         max_size = size/2 - 20;
1042         max_size = max_size * (max_depth - src_entry->depth) / max_depth;
1043         if (max_size == 0)
1044                 return 0;
1045         if (trg_entry->delta && trg_entry->delta_size <= max_size)
1046                 max_size = trg_entry->delta_size-1;
1047         src_size = src_entry->size;
1048         sizediff = src_size < size ? size - src_size : 0;
1049         if (sizediff >= max_size)
1050                 return 0;
1051
1052         delta_buf = create_delta(src_index, trg->data, size, &delta_size, max_size);
1053         if (!delta_buf)
1054                 return 0;
1055
1056         trg_entry->delta = src_entry;
1057         trg_entry->delta_size = delta_size;
1058         trg_entry->depth = src_entry->depth + 1;
1059         free(delta_buf);
1060         return 1;
1061 }
1062
1063 static void progress_interval(int signum)
1064 {
1065         progress_update = 1;
1066 }
1067
1068 static void find_deltas(struct object_entry **list, int window, int depth)
1069 {
1070         int i, idx;
1071         unsigned int array_size = window * sizeof(struct unpacked);
1072         struct unpacked *array = xmalloc(array_size);
1073         unsigned processed = 0;
1074         unsigned last_percent = 999;
1075
1076         memset(array, 0, array_size);
1077         i = nr_objects;
1078         idx = 0;
1079         if (progress)
1080                 fprintf(stderr, "Deltifying %d objects.\n", nr_result);
1081
1082         while (--i >= 0) {
1083                 struct object_entry *entry = list[i];
1084                 struct unpacked *n = array + idx;
1085                 unsigned long size;
1086                 char type[10];
1087                 int j;
1088
1089                 if (!entry->preferred_base)
1090                         processed++;
1091
1092                 if (progress) {
1093                         unsigned percent = processed * 100 / nr_result;
1094                         if (percent != last_percent || progress_update) {
1095                                 fprintf(stderr, "%4u%% (%u/%u) done\r",
1096                                         percent, processed, nr_result);
1097                                 progress_update = 0;
1098                                 last_percent = percent;
1099                         }
1100                 }
1101
1102                 if (entry->delta)
1103                         /* This happens if we decided to reuse existing
1104                          * delta from a pack.  "!no_reuse_delta &&" is implied.
1105                          */
1106                         continue;
1107
1108                 if (entry->size < 50)
1109                         continue;
1110                 free_delta_index(n->index);
1111                 n->index = NULL;
1112                 free(n->data);
1113                 n->entry = entry;
1114                 n->data = read_sha1_file(entry->sha1, type, &size);
1115                 if (size != entry->size)
1116                         die("object %s inconsistent object length (%lu vs %lu)",
1117                             sha1_to_hex(entry->sha1), size, entry->size);
1118
1119                 j = window;
1120                 while (--j > 0) {
1121                         unsigned int other_idx = idx + j;
1122                         struct unpacked *m;
1123                         if (other_idx >= window)
1124                                 other_idx -= window;
1125                         m = array + other_idx;
1126                         if (!m->entry)
1127                                 break;
1128                         if (try_delta(n, m, m->index, depth) < 0)
1129                                 break;
1130                 }
1131                 /* if we made n a delta, and if n is already at max
1132                  * depth, leaving it in the window is pointless.  we
1133                  * should evict it first.
1134                  */
1135                 if (entry->delta && depth <= entry->depth)
1136                         continue;
1137
1138                 n->index = create_delta_index(n->data, size);
1139                 if (!n->index)
1140                         die("out of memory");
1141
1142                 idx++;
1143                 if (idx >= window)
1144                         idx = 0;
1145         }
1146
1147         if (progress)
1148                 fputc('\n', stderr);
1149
1150         for (i = 0; i < window; ++i) {
1151                 free_delta_index(array[i].index);
1152                 free(array[i].data);
1153         }
1154         free(array);
1155 }
1156
1157 static void prepare_pack(int window, int depth)
1158 {
1159         get_object_details();
1160         sorted_by_type = create_sorted_list(type_size_sort);
1161         if (window && depth)
1162                 find_deltas(sorted_by_type, window+1, depth);
1163 }
1164
1165 static int reuse_cached_pack(unsigned char *sha1, int pack_to_stdout)
1166 {
1167         static const char cache[] = "pack-cache/pack-%s.%s";
1168         char *cached_pack, *cached_idx;
1169         int ifd, ofd, ifd_ix = -1;
1170
1171         cached_pack = git_path(cache, sha1_to_hex(sha1), "pack");
1172         ifd = open(cached_pack, O_RDONLY);
1173         if (ifd < 0)
1174                 return 0;
1175
1176         if (!pack_to_stdout) {
1177                 cached_idx = git_path(cache, sha1_to_hex(sha1), "idx");
1178                 ifd_ix = open(cached_idx, O_RDONLY);
1179                 if (ifd_ix < 0) {
1180                         close(ifd);
1181                         return 0;
1182                 }
1183         }
1184
1185         if (progress)
1186                 fprintf(stderr, "Reusing %d objects pack %s\n", nr_objects,
1187                         sha1_to_hex(sha1));
1188
1189         if (pack_to_stdout) {
1190                 if (copy_fd(ifd, 1))
1191                         exit(1);
1192                 close(ifd);
1193         }
1194         else {
1195                 char name[PATH_MAX];
1196                 snprintf(name, sizeof(name),
1197                          "%s-%s.%s", base_name, sha1_to_hex(sha1), "pack");
1198                 ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1199                 if (ofd < 0)
1200                         die("unable to open %s (%s)", name, strerror(errno));
1201                 if (copy_fd(ifd, ofd))
1202                         exit(1);
1203                 close(ifd);
1204
1205                 snprintf(name, sizeof(name),
1206                          "%s-%s.%s", base_name, sha1_to_hex(sha1), "idx");
1207                 ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1208                 if (ofd < 0)
1209                         die("unable to open %s (%s)", name, strerror(errno));
1210                 if (copy_fd(ifd_ix, ofd))
1211                         exit(1);
1212                 close(ifd_ix);
1213                 puts(sha1_to_hex(sha1));
1214         }
1215
1216         return 1;
1217 }
1218
1219 static void setup_progress_signal(void)
1220 {
1221         struct sigaction sa;
1222         struct itimerval v;
1223
1224         memset(&sa, 0, sizeof(sa));
1225         sa.sa_handler = progress_interval;
1226         sigemptyset(&sa.sa_mask);
1227         sa.sa_flags = SA_RESTART;
1228         sigaction(SIGALRM, &sa, NULL);
1229
1230         v.it_interval.tv_sec = 1;
1231         v.it_interval.tv_usec = 0;
1232         v.it_value = v.it_interval;
1233         setitimer(ITIMER_REAL, &v, NULL);
1234 }
1235
1236 int main(int argc, char **argv)
1237 {
1238         SHA_CTX ctx;
1239         char line[40 + 1 + PATH_MAX + 2];
1240         int window = 10, depth = 10, pack_to_stdout = 0;
1241         struct object_entry **list;
1242         int num_preferred_base = 0;
1243         int i;
1244
1245         setup_git_directory();
1246
1247         progress = isatty(2);
1248         for (i = 1; i < argc; i++) {
1249                 const char *arg = argv[i];
1250
1251                 if (*arg == '-') {
1252                         if (!strcmp("--non-empty", arg)) {
1253                                 non_empty = 1;
1254                                 continue;
1255                         }
1256                         if (!strcmp("--local", arg)) {
1257                                 local = 1;
1258                                 continue;
1259                         }
1260                         if (!strcmp("--incremental", arg)) {
1261                                 incremental = 1;
1262                                 continue;
1263                         }
1264                         if (!strncmp("--window=", arg, 9)) {
1265                                 char *end;
1266                                 window = strtoul(arg+9, &end, 0);
1267                                 if (!arg[9] || *end)
1268                                         usage(pack_usage);
1269                                 continue;
1270                         }
1271                         if (!strncmp("--depth=", arg, 8)) {
1272                                 char *end;
1273                                 depth = strtoul(arg+8, &end, 0);
1274                                 if (!arg[8] || *end)
1275                                         usage(pack_usage);
1276                                 continue;
1277                         }
1278                         if (!strcmp("--progress", arg)) {
1279                                 progress = 1;
1280                                 continue;
1281                         }
1282                         if (!strcmp("-q", arg)) {
1283                                 progress = 0;
1284                                 continue;
1285                         }
1286                         if (!strcmp("--no-reuse-delta", arg)) {
1287                                 no_reuse_delta = 1;
1288                                 continue;
1289                         }
1290                         if (!strcmp("--stdout", arg)) {
1291                                 pack_to_stdout = 1;
1292                                 continue;
1293                         }
1294                         usage(pack_usage);
1295                 }
1296                 if (base_name)
1297                         usage(pack_usage);
1298                 base_name = arg;
1299         }
1300
1301         if (pack_to_stdout != !base_name)
1302                 usage(pack_usage);
1303
1304         prepare_packed_git();
1305
1306         if (progress) {
1307                 fprintf(stderr, "Generating pack...\n");
1308                 setup_progress_signal();
1309         }
1310
1311         for (;;) {
1312                 unsigned char sha1[20];
1313                 unsigned hash;
1314
1315                 if (!fgets(line, sizeof(line), stdin)) {
1316                         if (feof(stdin))
1317                                 break;
1318                         if (!ferror(stdin))
1319                                 die("fgets returned NULL, not EOF, not error!");
1320                         if (errno != EINTR)
1321                                 die("fgets: %s", strerror(errno));
1322                         clearerr(stdin);
1323                         continue;
1324                 }
1325
1326                 if (line[0] == '-') {
1327                         if (get_sha1_hex(line+1, sha1))
1328                                 die("expected edge sha1, got garbage:\n %s",
1329                                     line+1);
1330                         if (num_preferred_base++ < window)
1331                                 add_preferred_base(sha1);
1332                         continue;
1333                 }
1334                 if (get_sha1_hex(line, sha1))
1335                         die("expected sha1, got garbage:\n %s", line);
1336                 hash = name_hash(NULL, line+41);
1337                 add_preferred_base_object(line+41, hash);
1338                 add_object_entry(sha1, hash, 0);
1339         }
1340         if (progress)
1341                 fprintf(stderr, "Done counting %d objects.\n", nr_objects);
1342         sorted_by_sha = create_final_object_list();
1343         if (non_empty && !nr_result)
1344                 return 0;
1345
1346         SHA1_Init(&ctx);
1347         list = sorted_by_sha;
1348         for (i = 0; i < nr_result; i++) {
1349                 struct object_entry *entry = *list++;
1350                 SHA1_Update(&ctx, entry->sha1, 20);
1351         }
1352         SHA1_Final(object_list_sha1, &ctx);
1353         if (progress && (nr_objects != nr_result))
1354                 fprintf(stderr, "Result has %d objects.\n", nr_result);
1355
1356         if (reuse_cached_pack(object_list_sha1, pack_to_stdout))
1357                 ;
1358         else {
1359                 if (nr_result)
1360                         prepare_pack(window, depth);
1361                 if (progress && pack_to_stdout) {
1362                         /* the other end usually displays progress itself */
1363                         struct itimerval v = {{0,},};
1364                         setitimer(ITIMER_REAL, &v, NULL);
1365                         signal(SIGALRM, SIG_IGN );
1366                         progress_update = 0;
1367                 }
1368                 write_pack_file();
1369                 if (!pack_to_stdout) {
1370                         write_index_file();
1371                         puts(sha1_to_hex(object_list_sha1));
1372                 }
1373         }
1374         if (progress)
1375                 fprintf(stderr, "Total %d, written %d (delta %d), reused %d (delta %d)\n",
1376                         nr_result, written, written_delta, reused, reused_delta);
1377         return 0;
1378 }