commit-graph: persist existence of changed-paths
[git] / commit-graph.c
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "pack.h"
5 #include "packfile.h"
6 #include "commit.h"
7 #include "object.h"
8 #include "refs.h"
9 #include "revision.h"
10 #include "sha1-lookup.h"
11 #include "commit-graph.h"
12 #include "object-store.h"
13 #include "alloc.h"
14 #include "hashmap.h"
15 #include "replace-object.h"
16 #include "progress.h"
17 #include "bloom.h"
18 #include "commit-slab.h"
19 #include "json-writer.h"
20 #include "trace2.h"
21
22 void git_test_write_commit_graph_or_die(void)
23 {
24         int flags = 0;
25         if (!git_env_bool(GIT_TEST_COMMIT_GRAPH, 0))
26                 return;
27
28         if (git_env_bool(GIT_TEST_COMMIT_GRAPH_CHANGED_PATHS, 0))
29                 flags = COMMIT_GRAPH_WRITE_BLOOM_FILTERS;
30
31         if (write_commit_graph_reachable(the_repository->objects->odb,
32                                          flags, NULL))
33                 die("failed to write commit-graph under GIT_TEST_COMMIT_GRAPH");
34 }
35
36 #define GRAPH_SIGNATURE 0x43475048 /* "CGPH" */
37 #define GRAPH_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
38 #define GRAPH_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
39 #define GRAPH_CHUNKID_DATA 0x43444154 /* "CDAT" */
40 #define GRAPH_CHUNKID_EXTRAEDGES 0x45444745 /* "EDGE" */
41 #define GRAPH_CHUNKID_BLOOMINDEXES 0x42494458 /* "BIDX" */
42 #define GRAPH_CHUNKID_BLOOMDATA 0x42444154 /* "BDAT" */
43 #define GRAPH_CHUNKID_BASE 0x42415345 /* "BASE" */
44 #define MAX_NUM_CHUNKS 7
45
46 #define GRAPH_DATA_WIDTH (the_hash_algo->rawsz + 16)
47
48 #define GRAPH_VERSION_1 0x1
49 #define GRAPH_VERSION GRAPH_VERSION_1
50
51 #define GRAPH_EXTRA_EDGES_NEEDED 0x80000000
52 #define GRAPH_EDGE_LAST_MASK 0x7fffffff
53 #define GRAPH_PARENT_NONE 0x70000000
54
55 #define GRAPH_LAST_EDGE 0x80000000
56
57 #define GRAPH_HEADER_SIZE 8
58 #define GRAPH_FANOUT_SIZE (4 * 256)
59 #define GRAPH_CHUNKLOOKUP_WIDTH 12
60 #define GRAPH_MIN_SIZE (GRAPH_HEADER_SIZE + 4 * GRAPH_CHUNKLOOKUP_WIDTH \
61                         + GRAPH_FANOUT_SIZE + the_hash_algo->rawsz)
62
63 /* Remember to update object flag allocation in object.h */
64 #define REACHABLE       (1u<<15)
65
66 /* Keep track of the order in which commits are added to our list. */
67 define_commit_slab(commit_pos, int);
68 static struct commit_pos commit_pos = COMMIT_SLAB_INIT(1, commit_pos);
69
70 static void set_commit_pos(struct repository *r, const struct object_id *oid)
71 {
72         static int32_t max_pos;
73         struct commit *commit = lookup_commit(r, oid);
74
75         if (!commit)
76                 return; /* should never happen, but be lenient */
77
78         *commit_pos_at(&commit_pos, commit) = max_pos++;
79 }
80
81 static int commit_pos_cmp(const void *va, const void *vb)
82 {
83         const struct commit *a = *(const struct commit **)va;
84         const struct commit *b = *(const struct commit **)vb;
85         return commit_pos_at(&commit_pos, a) -
86                commit_pos_at(&commit_pos, b);
87 }
88
89 static int commit_gen_cmp(const void *va, const void *vb)
90 {
91         const struct commit *a = *(const struct commit **)va;
92         const struct commit *b = *(const struct commit **)vb;
93
94         /* lower generation commits first */
95         if (a->generation < b->generation)
96                 return -1;
97         else if (a->generation > b->generation)
98                 return 1;
99
100         /* use date as a heuristic when generations are equal */
101         if (a->date < b->date)
102                 return -1;
103         else if (a->date > b->date)
104                 return 1;
105         return 0;
106 }
107
108 char *get_commit_graph_filename(struct object_directory *obj_dir)
109 {
110         return xstrfmt("%s/info/commit-graph", obj_dir->path);
111 }
112
113 static char *get_split_graph_filename(struct object_directory *odb,
114                                       const char *oid_hex)
115 {
116         return xstrfmt("%s/info/commit-graphs/graph-%s.graph", odb->path,
117                        oid_hex);
118 }
119
120 static char *get_chain_filename(struct object_directory *odb)
121 {
122         return xstrfmt("%s/info/commit-graphs/commit-graph-chain", odb->path);
123 }
124
125 static uint8_t oid_version(void)
126 {
127         return 1;
128 }
129
130 static struct commit_graph *alloc_commit_graph(void)
131 {
132         struct commit_graph *g = xcalloc(1, sizeof(*g));
133         g->graph_fd = -1;
134
135         return g;
136 }
137
138 extern int read_replace_refs;
139
140 static int commit_graph_compatible(struct repository *r)
141 {
142         if (!r->gitdir)
143                 return 0;
144
145         if (read_replace_refs) {
146                 prepare_replace_object(r);
147                 if (hashmap_get_size(&r->objects->replace_map->map))
148                         return 0;
149         }
150
151         prepare_commit_graft(r);
152         if (r->parsed_objects && r->parsed_objects->grafts_nr)
153                 return 0;
154         if (is_repository_shallow(r))
155                 return 0;
156
157         return 1;
158 }
159
160 int open_commit_graph(const char *graph_file, int *fd, struct stat *st)
161 {
162         *fd = git_open(graph_file);
163         if (*fd < 0)
164                 return 0;
165         if (fstat(*fd, st)) {
166                 close(*fd);
167                 return 0;
168         }
169         return 1;
170 }
171
172 struct commit_graph *load_commit_graph_one_fd_st(int fd, struct stat *st,
173                                                  struct object_directory *odb)
174 {
175         void *graph_map;
176         size_t graph_size;
177         struct commit_graph *ret;
178
179         graph_size = xsize_t(st->st_size);
180
181         if (graph_size < GRAPH_MIN_SIZE) {
182                 close(fd);
183                 error(_("commit-graph file is too small"));
184                 return NULL;
185         }
186         graph_map = xmmap(NULL, graph_size, PROT_READ, MAP_PRIVATE, fd, 0);
187         ret = parse_commit_graph(graph_map, fd, graph_size);
188
189         if (ret)
190                 ret->odb = odb;
191         else {
192                 munmap(graph_map, graph_size);
193                 close(fd);
194         }
195
196         return ret;
197 }
198
199 static int verify_commit_graph_lite(struct commit_graph *g)
200 {
201         /*
202          * Basic validation shared between parse_commit_graph()
203          * which'll be called every time the graph is used, and the
204          * much more expensive verify_commit_graph() used by
205          * "commit-graph verify".
206          *
207          * There should only be very basic checks here to ensure that
208          * we don't e.g. segfault in fill_commit_in_graph(), but
209          * because this is a very hot codepath nothing that e.g. loops
210          * over g->num_commits, or runs a checksum on the commit-graph
211          * itself.
212          */
213         if (!g->chunk_oid_fanout) {
214                 error("commit-graph is missing the OID Fanout chunk");
215                 return 1;
216         }
217         if (!g->chunk_oid_lookup) {
218                 error("commit-graph is missing the OID Lookup chunk");
219                 return 1;
220         }
221         if (!g->chunk_commit_data) {
222                 error("commit-graph is missing the Commit Data chunk");
223                 return 1;
224         }
225
226         return 0;
227 }
228
229 struct commit_graph *parse_commit_graph(void *graph_map, int fd,
230                                         size_t graph_size)
231 {
232         const unsigned char *data, *chunk_lookup;
233         uint32_t i;
234         struct commit_graph *graph;
235         uint64_t next_chunk_offset;
236         uint32_t graph_signature;
237         unsigned char graph_version, hash_version;
238
239         if (!graph_map)
240                 return NULL;
241
242         if (graph_size < GRAPH_MIN_SIZE)
243                 return NULL;
244
245         data = (const unsigned char *)graph_map;
246
247         graph_signature = get_be32(data);
248         if (graph_signature != GRAPH_SIGNATURE) {
249                 error(_("commit-graph signature %X does not match signature %X"),
250                       graph_signature, GRAPH_SIGNATURE);
251                 return NULL;
252         }
253
254         graph_version = *(unsigned char*)(data + 4);
255         if (graph_version != GRAPH_VERSION) {
256                 error(_("commit-graph version %X does not match version %X"),
257                       graph_version, GRAPH_VERSION);
258                 return NULL;
259         }
260
261         hash_version = *(unsigned char*)(data + 5);
262         if (hash_version != oid_version()) {
263                 error(_("commit-graph hash version %X does not match version %X"),
264                       hash_version, oid_version());
265                 return NULL;
266         }
267
268         graph = alloc_commit_graph();
269
270         graph->hash_len = the_hash_algo->rawsz;
271         graph->num_chunks = *(unsigned char*)(data + 6);
272         graph->graph_fd = fd;
273         graph->data = graph_map;
274         graph->data_len = graph_size;
275
276         if (graph_size < GRAPH_HEADER_SIZE +
277                          (graph->num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH +
278                          GRAPH_FANOUT_SIZE + the_hash_algo->rawsz) {
279                 error(_("commit-graph file is too small to hold %u chunks"),
280                       graph->num_chunks);
281                 free(graph);
282                 return NULL;
283         }
284
285         chunk_lookup = data + 8;
286         next_chunk_offset = get_be64(chunk_lookup + 4);
287         for (i = 0; i < graph->num_chunks; i++) {
288                 uint32_t chunk_id;
289                 uint64_t chunk_offset = next_chunk_offset;
290                 int chunk_repeated = 0;
291
292                 chunk_id = get_be32(chunk_lookup + 0);
293
294                 chunk_lookup += GRAPH_CHUNKLOOKUP_WIDTH;
295                 next_chunk_offset = get_be64(chunk_lookup + 4);
296
297                 if (chunk_offset > graph_size - the_hash_algo->rawsz) {
298                         error(_("commit-graph improper chunk offset %08x%08x"), (uint32_t)(chunk_offset >> 32),
299                               (uint32_t)chunk_offset);
300                         free(graph);
301                         return NULL;
302                 }
303
304                 switch (chunk_id) {
305                 case GRAPH_CHUNKID_OIDFANOUT:
306                         if (graph->chunk_oid_fanout)
307                                 chunk_repeated = 1;
308                         else
309                                 graph->chunk_oid_fanout = (uint32_t*)(data + chunk_offset);
310                         break;
311
312                 case GRAPH_CHUNKID_OIDLOOKUP:
313                         if (graph->chunk_oid_lookup)
314                                 chunk_repeated = 1;
315                         else {
316                                 graph->chunk_oid_lookup = data + chunk_offset;
317                                 graph->num_commits = (next_chunk_offset - chunk_offset)
318                                                      / graph->hash_len;
319                         }
320                         break;
321
322                 case GRAPH_CHUNKID_DATA:
323                         if (graph->chunk_commit_data)
324                                 chunk_repeated = 1;
325                         else
326                                 graph->chunk_commit_data = data + chunk_offset;
327                         break;
328
329                 case GRAPH_CHUNKID_EXTRAEDGES:
330                         if (graph->chunk_extra_edges)
331                                 chunk_repeated = 1;
332                         else
333                                 graph->chunk_extra_edges = data + chunk_offset;
334                         break;
335
336                 case GRAPH_CHUNKID_BASE:
337                         if (graph->chunk_base_graphs)
338                                 chunk_repeated = 1;
339                         else
340                                 graph->chunk_base_graphs = data + chunk_offset;
341                         break;
342
343                 case GRAPH_CHUNKID_BLOOMINDEXES:
344                         if (graph->chunk_bloom_indexes)
345                                 chunk_repeated = 1;
346                         else
347                                 graph->chunk_bloom_indexes = data + chunk_offset;
348                         break;
349
350                 case GRAPH_CHUNKID_BLOOMDATA:
351                         if (graph->chunk_bloom_data)
352                                 chunk_repeated = 1;
353                         else {
354                                 uint32_t hash_version;
355                                 graph->chunk_bloom_data = data + chunk_offset;
356                                 hash_version = get_be32(data + chunk_offset);
357
358                                 if (hash_version != 1)
359                                         break;
360
361                                 graph->bloom_filter_settings = xmalloc(sizeof(struct bloom_filter_settings));
362                                 graph->bloom_filter_settings->hash_version = hash_version;
363                                 graph->bloom_filter_settings->num_hashes = get_be32(data + chunk_offset + 4);
364                                 graph->bloom_filter_settings->bits_per_entry = get_be32(data + chunk_offset + 8);
365                         }
366                         break;
367                 }
368
369                 if (chunk_repeated) {
370                         error(_("commit-graph chunk id %08x appears multiple times"), chunk_id);
371                         free(graph);
372                         return NULL;
373                 }
374         }
375
376         if (graph->chunk_bloom_indexes && graph->chunk_bloom_data) {
377                 init_bloom_filters();
378         } else {
379                 /* We need both the bloom chunks to exist together. Else ignore the data */
380                 graph->chunk_bloom_indexes = NULL;
381                 graph->chunk_bloom_data = NULL;
382                 graph->bloom_filter_settings = NULL;
383         }
384
385         hashcpy(graph->oid.hash, graph->data + graph->data_len - graph->hash_len);
386
387         if (verify_commit_graph_lite(graph)) {
388                 free(graph);
389                 return NULL;
390         }
391
392         return graph;
393 }
394
395 static struct commit_graph *load_commit_graph_one(const char *graph_file,
396                                                   struct object_directory *odb)
397 {
398
399         struct stat st;
400         int fd;
401         struct commit_graph *g;
402         int open_ok = open_commit_graph(graph_file, &fd, &st);
403
404         if (!open_ok)
405                 return NULL;
406
407         g = load_commit_graph_one_fd_st(fd, &st, odb);
408
409         if (g)
410                 g->filename = xstrdup(graph_file);
411
412         return g;
413 }
414
415 static struct commit_graph *load_commit_graph_v1(struct repository *r,
416                                                  struct object_directory *odb)
417 {
418         char *graph_name = get_commit_graph_filename(odb);
419         struct commit_graph *g = load_commit_graph_one(graph_name, odb);
420         free(graph_name);
421
422         return g;
423 }
424
425 static int add_graph_to_chain(struct commit_graph *g,
426                               struct commit_graph *chain,
427                               struct object_id *oids,
428                               int n)
429 {
430         struct commit_graph *cur_g = chain;
431
432         if (n && !g->chunk_base_graphs) {
433                 warning(_("commit-graph has no base graphs chunk"));
434                 return 0;
435         }
436
437         while (n) {
438                 n--;
439
440                 if (!cur_g ||
441                     !oideq(&oids[n], &cur_g->oid) ||
442                     !hasheq(oids[n].hash, g->chunk_base_graphs + g->hash_len * n)) {
443                         warning(_("commit-graph chain does not match"));
444                         return 0;
445                 }
446
447                 cur_g = cur_g->base_graph;
448         }
449
450         g->base_graph = chain;
451
452         if (chain)
453                 g->num_commits_in_base = chain->num_commits + chain->num_commits_in_base;
454
455         return 1;
456 }
457
458 static struct commit_graph *load_commit_graph_chain(struct repository *r,
459                                                     struct object_directory *odb)
460 {
461         struct commit_graph *graph_chain = NULL;
462         struct strbuf line = STRBUF_INIT;
463         struct stat st;
464         struct object_id *oids;
465         int i = 0, valid = 1, count;
466         char *chain_name = get_chain_filename(odb);
467         FILE *fp;
468         int stat_res;
469
470         fp = fopen(chain_name, "r");
471         stat_res = stat(chain_name, &st);
472         free(chain_name);
473
474         if (!fp ||
475             stat_res ||
476             st.st_size <= the_hash_algo->hexsz)
477                 return NULL;
478
479         count = st.st_size / (the_hash_algo->hexsz + 1);
480         oids = xcalloc(count, sizeof(struct object_id));
481
482         prepare_alt_odb(r);
483
484         for (i = 0; i < count; i++) {
485                 struct object_directory *odb;
486
487                 if (strbuf_getline_lf(&line, fp) == EOF)
488                         break;
489
490                 if (get_oid_hex(line.buf, &oids[i])) {
491                         warning(_("invalid commit-graph chain: line '%s' not a hash"),
492                                 line.buf);
493                         valid = 0;
494                         break;
495                 }
496
497                 valid = 0;
498                 for (odb = r->objects->odb; odb; odb = odb->next) {
499                         char *graph_name = get_split_graph_filename(odb, line.buf);
500                         struct commit_graph *g = load_commit_graph_one(graph_name, odb);
501
502                         free(graph_name);
503
504                         if (g) {
505                                 if (add_graph_to_chain(g, graph_chain, oids, i)) {
506                                         graph_chain = g;
507                                         valid = 1;
508                                 }
509
510                                 break;
511                         }
512                 }
513
514                 if (!valid) {
515                         warning(_("unable to find all commit-graph files"));
516                         break;
517                 }
518         }
519
520         free(oids);
521         fclose(fp);
522         strbuf_release(&line);
523
524         return graph_chain;
525 }
526
527 struct commit_graph *read_commit_graph_one(struct repository *r,
528                                            struct object_directory *odb)
529 {
530         struct commit_graph *g = load_commit_graph_v1(r, odb);
531
532         if (!g)
533                 g = load_commit_graph_chain(r, odb);
534
535         return g;
536 }
537
538 static void prepare_commit_graph_one(struct repository *r,
539                                      struct object_directory *odb)
540 {
541
542         if (r->objects->commit_graph)
543                 return;
544
545         r->objects->commit_graph = read_commit_graph_one(r, odb);
546 }
547
548 /*
549  * Return 1 if commit_graph is non-NULL, and 0 otherwise.
550  *
551  * On the first invocation, this function attempts to load the commit
552  * graph if the_repository is configured to have one.
553  */
554 static int prepare_commit_graph(struct repository *r)
555 {
556         struct object_directory *odb;
557
558         /*
559          * This must come before the "already attempted?" check below, because
560          * we want to disable even an already-loaded graph file.
561          */
562         if (r->commit_graph_disabled)
563                 return 0;
564
565         if (r->objects->commit_graph_attempted)
566                 return !!r->objects->commit_graph;
567         r->objects->commit_graph_attempted = 1;
568
569         prepare_repo_settings(r);
570
571         if (!git_env_bool(GIT_TEST_COMMIT_GRAPH, 0) &&
572             r->settings.core_commit_graph != 1)
573                 /*
574                  * This repository is not configured to use commit graphs, so
575                  * do not load one. (But report commit_graph_attempted anyway
576                  * so that commit graph loading is not attempted again for this
577                  * repository.)
578                  */
579                 return 0;
580
581         if (!commit_graph_compatible(r))
582                 return 0;
583
584         prepare_alt_odb(r);
585         for (odb = r->objects->odb;
586              !r->objects->commit_graph && odb;
587              odb = odb->next)
588                 prepare_commit_graph_one(r, odb);
589         return !!r->objects->commit_graph;
590 }
591
592 int generation_numbers_enabled(struct repository *r)
593 {
594         uint32_t first_generation;
595         struct commit_graph *g;
596         if (!prepare_commit_graph(r))
597                return 0;
598
599         g = r->objects->commit_graph;
600
601         if (!g->num_commits)
602                 return 0;
603
604         first_generation = get_be32(g->chunk_commit_data +
605                                     g->hash_len + 8) >> 2;
606
607         return !!first_generation;
608 }
609
610 static void close_commit_graph_one(struct commit_graph *g)
611 {
612         if (!g)
613                 return;
614
615         close_commit_graph_one(g->base_graph);
616         free_commit_graph(g);
617 }
618
619 void close_commit_graph(struct raw_object_store *o)
620 {
621         close_commit_graph_one(o->commit_graph);
622         o->commit_graph = NULL;
623 }
624
625 static int bsearch_graph(struct commit_graph *g, struct object_id *oid, uint32_t *pos)
626 {
627         return bsearch_hash(oid->hash, g->chunk_oid_fanout,
628                             g->chunk_oid_lookup, g->hash_len, pos);
629 }
630
631 static void load_oid_from_graph(struct commit_graph *g,
632                                 uint32_t pos,
633                                 struct object_id *oid)
634 {
635         uint32_t lex_index;
636
637         while (g && pos < g->num_commits_in_base)
638                 g = g->base_graph;
639
640         if (!g)
641                 BUG("NULL commit-graph");
642
643         if (pos >= g->num_commits + g->num_commits_in_base)
644                 die(_("invalid commit position. commit-graph is likely corrupt"));
645
646         lex_index = pos - g->num_commits_in_base;
647
648         hashcpy(oid->hash, g->chunk_oid_lookup + g->hash_len * lex_index);
649 }
650
651 static struct commit_list **insert_parent_or_die(struct repository *r,
652                                                  struct commit_graph *g,
653                                                  uint32_t pos,
654                                                  struct commit_list **pptr)
655 {
656         struct commit *c;
657         struct object_id oid;
658
659         if (pos >= g->num_commits + g->num_commits_in_base)
660                 die("invalid parent position %"PRIu32, pos);
661
662         load_oid_from_graph(g, pos, &oid);
663         c = lookup_commit(r, &oid);
664         if (!c)
665                 die(_("could not find commit %s"), oid_to_hex(&oid));
666         c->graph_pos = pos;
667         return &commit_list_insert(c, pptr)->next;
668 }
669
670 static void fill_commit_graph_info(struct commit *item, struct commit_graph *g, uint32_t pos)
671 {
672         const unsigned char *commit_data;
673         uint32_t lex_index;
674
675         while (pos < g->num_commits_in_base)
676                 g = g->base_graph;
677
678         lex_index = pos - g->num_commits_in_base;
679         commit_data = g->chunk_commit_data + GRAPH_DATA_WIDTH * lex_index;
680         item->graph_pos = pos;
681         item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
682 }
683
684 static inline void set_commit_tree(struct commit *c, struct tree *t)
685 {
686         c->maybe_tree = t;
687 }
688
689 static int fill_commit_in_graph(struct repository *r,
690                                 struct commit *item,
691                                 struct commit_graph *g, uint32_t pos)
692 {
693         uint32_t edge_value;
694         uint32_t *parent_data_ptr;
695         uint64_t date_low, date_high;
696         struct commit_list **pptr;
697         const unsigned char *commit_data;
698         uint32_t lex_index;
699
700         while (pos < g->num_commits_in_base)
701                 g = g->base_graph;
702
703         if (pos >= g->num_commits + g->num_commits_in_base)
704                 die(_("invalid commit position. commit-graph is likely corrupt"));
705
706         /*
707          * Store the "full" position, but then use the
708          * "local" position for the rest of the calculation.
709          */
710         item->graph_pos = pos;
711         lex_index = pos - g->num_commits_in_base;
712
713         commit_data = g->chunk_commit_data + (g->hash_len + 16) * lex_index;
714
715         item->object.parsed = 1;
716
717         set_commit_tree(item, NULL);
718
719         date_high = get_be32(commit_data + g->hash_len + 8) & 0x3;
720         date_low = get_be32(commit_data + g->hash_len + 12);
721         item->date = (timestamp_t)((date_high << 32) | date_low);
722
723         item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
724
725         pptr = &item->parents;
726
727         edge_value = get_be32(commit_data + g->hash_len);
728         if (edge_value == GRAPH_PARENT_NONE)
729                 return 1;
730         pptr = insert_parent_or_die(r, g, edge_value, pptr);
731
732         edge_value = get_be32(commit_data + g->hash_len + 4);
733         if (edge_value == GRAPH_PARENT_NONE)
734                 return 1;
735         if (!(edge_value & GRAPH_EXTRA_EDGES_NEEDED)) {
736                 pptr = insert_parent_or_die(r, g, edge_value, pptr);
737                 return 1;
738         }
739
740         parent_data_ptr = (uint32_t*)(g->chunk_extra_edges +
741                           4 * (uint64_t)(edge_value & GRAPH_EDGE_LAST_MASK));
742         do {
743                 edge_value = get_be32(parent_data_ptr);
744                 pptr = insert_parent_or_die(r, g,
745                                             edge_value & GRAPH_EDGE_LAST_MASK,
746                                             pptr);
747                 parent_data_ptr++;
748         } while (!(edge_value & GRAPH_LAST_EDGE));
749
750         return 1;
751 }
752
753 static int find_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t *pos)
754 {
755         if (item->graph_pos != COMMIT_NOT_FROM_GRAPH) {
756                 *pos = item->graph_pos;
757                 return 1;
758         } else {
759                 struct commit_graph *cur_g = g;
760                 uint32_t lex_index;
761
762                 while (cur_g && !bsearch_graph(cur_g, &(item->object.oid), &lex_index))
763                         cur_g = cur_g->base_graph;
764
765                 if (cur_g) {
766                         *pos = lex_index + cur_g->num_commits_in_base;
767                         return 1;
768                 }
769
770                 return 0;
771         }
772 }
773
774 static int parse_commit_in_graph_one(struct repository *r,
775                                      struct commit_graph *g,
776                                      struct commit *item)
777 {
778         uint32_t pos;
779
780         if (item->object.parsed)
781                 return 1;
782
783         if (find_commit_in_graph(item, g, &pos))
784                 return fill_commit_in_graph(r, item, g, pos);
785
786         return 0;
787 }
788
789 int parse_commit_in_graph(struct repository *r, struct commit *item)
790 {
791         static int checked_env = 0;
792
793         if (!checked_env &&
794             git_env_bool(GIT_TEST_COMMIT_GRAPH_DIE_ON_PARSE, 0))
795                 die("dying as requested by the '%s' variable on commit-graph parse!",
796                     GIT_TEST_COMMIT_GRAPH_DIE_ON_PARSE);
797         checked_env = 1;
798
799         if (!prepare_commit_graph(r))
800                 return 0;
801         return parse_commit_in_graph_one(r, r->objects->commit_graph, item);
802 }
803
804 void load_commit_graph_info(struct repository *r, struct commit *item)
805 {
806         uint32_t pos;
807         if (!prepare_commit_graph(r))
808                 return;
809         if (find_commit_in_graph(item, r->objects->commit_graph, &pos))
810                 fill_commit_graph_info(item, r->objects->commit_graph, pos);
811 }
812
813 static struct tree *load_tree_for_commit(struct repository *r,
814                                          struct commit_graph *g,
815                                          struct commit *c)
816 {
817         struct object_id oid;
818         const unsigned char *commit_data;
819
820         while (c->graph_pos < g->num_commits_in_base)
821                 g = g->base_graph;
822
823         commit_data = g->chunk_commit_data +
824                         GRAPH_DATA_WIDTH * (c->graph_pos - g->num_commits_in_base);
825
826         hashcpy(oid.hash, commit_data);
827         set_commit_tree(c, lookup_tree(r, &oid));
828
829         return c->maybe_tree;
830 }
831
832 static struct tree *get_commit_tree_in_graph_one(struct repository *r,
833                                                  struct commit_graph *g,
834                                                  const struct commit *c)
835 {
836         if (c->maybe_tree)
837                 return c->maybe_tree;
838         if (c->graph_pos == COMMIT_NOT_FROM_GRAPH)
839                 BUG("get_commit_tree_in_graph_one called from non-commit-graph commit");
840
841         return load_tree_for_commit(r, g, (struct commit *)c);
842 }
843
844 struct tree *get_commit_tree_in_graph(struct repository *r, const struct commit *c)
845 {
846         return get_commit_tree_in_graph_one(r, r->objects->commit_graph, c);
847 }
848
849 struct packed_commit_list {
850         struct commit **list;
851         int nr;
852         int alloc;
853 };
854
855 struct packed_oid_list {
856         struct object_id *list;
857         int nr;
858         int alloc;
859 };
860
861 struct write_commit_graph_context {
862         struct repository *r;
863         struct object_directory *odb;
864         char *graph_name;
865         struct packed_oid_list oids;
866         struct packed_commit_list commits;
867         int num_extra_edges;
868         unsigned long approx_nr_objects;
869         struct progress *progress;
870         int progress_done;
871         uint64_t progress_cnt;
872
873         char *base_graph_name;
874         int num_commit_graphs_before;
875         int num_commit_graphs_after;
876         char **commit_graph_filenames_before;
877         char **commit_graph_filenames_after;
878         char **commit_graph_hash_after;
879         uint32_t new_num_commits_in_base;
880         struct commit_graph *new_base_graph;
881
882         unsigned append:1,
883                  report_progress:1,
884                  split:1,
885                  check_oids:1,
886                  changed_paths:1,
887                  order_by_pack:1;
888
889         const struct split_commit_graph_opts *split_opts;
890         size_t total_bloom_filter_data_size;
891         const struct bloom_filter_settings *bloom_settings;
892 };
893
894 static void write_graph_chunk_fanout(struct hashfile *f,
895                                      struct write_commit_graph_context *ctx)
896 {
897         int i, count = 0;
898         struct commit **list = ctx->commits.list;
899
900         /*
901          * Write the first-level table (the list is sorted,
902          * but we use a 256-entry lookup to be able to avoid
903          * having to do eight extra binary search iterations).
904          */
905         for (i = 0; i < 256; i++) {
906                 while (count < ctx->commits.nr) {
907                         if ((*list)->object.oid.hash[0] != i)
908                                 break;
909                         display_progress(ctx->progress, ++ctx->progress_cnt);
910                         count++;
911                         list++;
912                 }
913
914                 hashwrite_be32(f, count);
915         }
916 }
917
918 static void write_graph_chunk_oids(struct hashfile *f, int hash_len,
919                                    struct write_commit_graph_context *ctx)
920 {
921         struct commit **list = ctx->commits.list;
922         int count;
923         for (count = 0; count < ctx->commits.nr; count++, list++) {
924                 display_progress(ctx->progress, ++ctx->progress_cnt);
925                 hashwrite(f, (*list)->object.oid.hash, (int)hash_len);
926         }
927 }
928
929 static const unsigned char *commit_to_sha1(size_t index, void *table)
930 {
931         struct commit **commits = table;
932         return commits[index]->object.oid.hash;
933 }
934
935 static void write_graph_chunk_data(struct hashfile *f, int hash_len,
936                                    struct write_commit_graph_context *ctx)
937 {
938         struct commit **list = ctx->commits.list;
939         struct commit **last = ctx->commits.list + ctx->commits.nr;
940         uint32_t num_extra_edges = 0;
941
942         while (list < last) {
943                 struct commit_list *parent;
944                 struct object_id *tree;
945                 int edge_value;
946                 uint32_t packedDate[2];
947                 display_progress(ctx->progress, ++ctx->progress_cnt);
948
949                 if (parse_commit_no_graph(*list))
950                         die(_("unable to parse commit %s"),
951                                 oid_to_hex(&(*list)->object.oid));
952                 tree = get_commit_tree_oid(*list);
953                 hashwrite(f, tree->hash, hash_len);
954
955                 parent = (*list)->parents;
956
957                 if (!parent)
958                         edge_value = GRAPH_PARENT_NONE;
959                 else {
960                         edge_value = sha1_pos(parent->item->object.oid.hash,
961                                               ctx->commits.list,
962                                               ctx->commits.nr,
963                                               commit_to_sha1);
964
965                         if (edge_value >= 0)
966                                 edge_value += ctx->new_num_commits_in_base;
967                         else {
968                                 uint32_t pos;
969                                 if (find_commit_in_graph(parent->item,
970                                                          ctx->new_base_graph,
971                                                          &pos))
972                                         edge_value = pos;
973                         }
974
975                         if (edge_value < 0)
976                                 BUG("missing parent %s for commit %s",
977                                     oid_to_hex(&parent->item->object.oid),
978                                     oid_to_hex(&(*list)->object.oid));
979                 }
980
981                 hashwrite_be32(f, edge_value);
982
983                 if (parent)
984                         parent = parent->next;
985
986                 if (!parent)
987                         edge_value = GRAPH_PARENT_NONE;
988                 else if (parent->next)
989                         edge_value = GRAPH_EXTRA_EDGES_NEEDED | num_extra_edges;
990                 else {
991                         edge_value = sha1_pos(parent->item->object.oid.hash,
992                                               ctx->commits.list,
993                                               ctx->commits.nr,
994                                               commit_to_sha1);
995
996                         if (edge_value >= 0)
997                                 edge_value += ctx->new_num_commits_in_base;
998                         else {
999                                 uint32_t pos;
1000                                 if (find_commit_in_graph(parent->item,
1001                                                          ctx->new_base_graph,
1002                                                          &pos))
1003                                         edge_value = pos;
1004                         }
1005
1006                         if (edge_value < 0)
1007                                 BUG("missing parent %s for commit %s",
1008                                     oid_to_hex(&parent->item->object.oid),
1009                                     oid_to_hex(&(*list)->object.oid));
1010                 }
1011
1012                 hashwrite_be32(f, edge_value);
1013
1014                 if (edge_value & GRAPH_EXTRA_EDGES_NEEDED) {
1015                         do {
1016                                 num_extra_edges++;
1017                                 parent = parent->next;
1018                         } while (parent);
1019                 }
1020
1021                 if (sizeof((*list)->date) > 4)
1022                         packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
1023                 else
1024                         packedDate[0] = 0;
1025
1026                 packedDate[0] |= htonl((*list)->generation << 2);
1027
1028                 packedDate[1] = htonl((*list)->date);
1029                 hashwrite(f, packedDate, 8);
1030
1031                 list++;
1032         }
1033 }
1034
1035 static void write_graph_chunk_extra_edges(struct hashfile *f,
1036                                           struct write_commit_graph_context *ctx)
1037 {
1038         struct commit **list = ctx->commits.list;
1039         struct commit **last = ctx->commits.list + ctx->commits.nr;
1040         struct commit_list *parent;
1041
1042         while (list < last) {
1043                 int num_parents = 0;
1044
1045                 display_progress(ctx->progress, ++ctx->progress_cnt);
1046
1047                 for (parent = (*list)->parents; num_parents < 3 && parent;
1048                      parent = parent->next)
1049                         num_parents++;
1050
1051                 if (num_parents <= 2) {
1052                         list++;
1053                         continue;
1054                 }
1055
1056                 /* Since num_parents > 2, this initializer is safe. */
1057                 for (parent = (*list)->parents->next; parent; parent = parent->next) {
1058                         int edge_value = sha1_pos(parent->item->object.oid.hash,
1059                                                   ctx->commits.list,
1060                                                   ctx->commits.nr,
1061                                                   commit_to_sha1);
1062
1063                         if (edge_value >= 0)
1064                                 edge_value += ctx->new_num_commits_in_base;
1065                         else {
1066                                 uint32_t pos;
1067                                 if (find_commit_in_graph(parent->item,
1068                                                          ctx->new_base_graph,
1069                                                          &pos))
1070                                         edge_value = pos;
1071                         }
1072
1073                         if (edge_value < 0)
1074                                 BUG("missing parent %s for commit %s",
1075                                     oid_to_hex(&parent->item->object.oid),
1076                                     oid_to_hex(&(*list)->object.oid));
1077                         else if (!parent->next)
1078                                 edge_value |= GRAPH_LAST_EDGE;
1079
1080                         hashwrite_be32(f, edge_value);
1081                 }
1082
1083                 list++;
1084         }
1085 }
1086
1087 static void write_graph_chunk_bloom_indexes(struct hashfile *f,
1088                                             struct write_commit_graph_context *ctx)
1089 {
1090         struct commit **list = ctx->commits.list;
1091         struct commit **last = ctx->commits.list + ctx->commits.nr;
1092         uint32_t cur_pos = 0;
1093         struct progress *progress = NULL;
1094         int i = 0;
1095
1096         if (ctx->report_progress)
1097                 progress = start_delayed_progress(
1098                         _("Writing changed paths Bloom filters index"),
1099                         ctx->commits.nr);
1100
1101         while (list < last) {
1102                 struct bloom_filter *filter = get_bloom_filter(ctx->r, *list, 0);
1103                 size_t len = filter ? filter->len : 0;
1104                 cur_pos += len;
1105                 display_progress(progress, ++i);
1106                 hashwrite_be32(f, cur_pos);
1107                 list++;
1108         }
1109
1110         stop_progress(&progress);
1111 }
1112
1113 static void trace2_bloom_filter_settings(struct write_commit_graph_context *ctx)
1114 {
1115         struct json_writer jw = JSON_WRITER_INIT;
1116
1117         jw_object_begin(&jw, 0);
1118         jw_object_intmax(&jw, "hash_version", ctx->bloom_settings->hash_version);
1119         jw_object_intmax(&jw, "num_hashes", ctx->bloom_settings->num_hashes);
1120         jw_object_intmax(&jw, "bits_per_entry", ctx->bloom_settings->bits_per_entry);
1121         jw_end(&jw);
1122
1123         trace2_data_json("bloom", ctx->r, "settings", &jw);
1124
1125         jw_release(&jw);
1126 }
1127
1128 static void write_graph_chunk_bloom_data(struct hashfile *f,
1129                                          struct write_commit_graph_context *ctx)
1130 {
1131         struct commit **list = ctx->commits.list;
1132         struct commit **last = ctx->commits.list + ctx->commits.nr;
1133         struct progress *progress = NULL;
1134         int i = 0;
1135
1136         trace2_bloom_filter_settings(ctx);
1137
1138         if (ctx->report_progress)
1139                 progress = start_delayed_progress(
1140                         _("Writing changed paths Bloom filters data"),
1141                         ctx->commits.nr);
1142
1143         hashwrite_be32(f, ctx->bloom_settings->hash_version);
1144         hashwrite_be32(f, ctx->bloom_settings->num_hashes);
1145         hashwrite_be32(f, ctx->bloom_settings->bits_per_entry);
1146
1147         while (list < last) {
1148                 struct bloom_filter *filter = get_bloom_filter(ctx->r, *list, 0);
1149                 size_t len = filter ? filter->len : 0;
1150                 display_progress(progress, ++i);
1151
1152                 if (len)
1153                         hashwrite(f, filter->data, len * sizeof(unsigned char));
1154                 list++;
1155         }
1156
1157         stop_progress(&progress);
1158 }
1159
1160 static int oid_compare(const void *_a, const void *_b)
1161 {
1162         const struct object_id *a = (const struct object_id *)_a;
1163         const struct object_id *b = (const struct object_id *)_b;
1164         return oidcmp(a, b);
1165 }
1166
1167 static int add_packed_commits(const struct object_id *oid,
1168                               struct packed_git *pack,
1169                               uint32_t pos,
1170                               void *data)
1171 {
1172         struct write_commit_graph_context *ctx = (struct write_commit_graph_context*)data;
1173         enum object_type type;
1174         off_t offset = nth_packed_object_offset(pack, pos);
1175         struct object_info oi = OBJECT_INFO_INIT;
1176
1177         if (ctx->progress)
1178                 display_progress(ctx->progress, ++ctx->progress_done);
1179
1180         oi.typep = &type;
1181         if (packed_object_info(ctx->r, pack, offset, &oi) < 0)
1182                 die(_("unable to get type of object %s"), oid_to_hex(oid));
1183
1184         if (type != OBJ_COMMIT)
1185                 return 0;
1186
1187         ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
1188         oidcpy(&(ctx->oids.list[ctx->oids.nr]), oid);
1189         ctx->oids.nr++;
1190
1191         set_commit_pos(ctx->r, oid);
1192
1193         return 0;
1194 }
1195
1196 static void add_missing_parents(struct write_commit_graph_context *ctx, struct commit *commit)
1197 {
1198         struct commit_list *parent;
1199         for (parent = commit->parents; parent; parent = parent->next) {
1200                 if (!(parent->item->object.flags & REACHABLE)) {
1201                         ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
1202                         oidcpy(&ctx->oids.list[ctx->oids.nr], &(parent->item->object.oid));
1203                         ctx->oids.nr++;
1204                         parent->item->object.flags |= REACHABLE;
1205                 }
1206         }
1207 }
1208
1209 static void close_reachable(struct write_commit_graph_context *ctx)
1210 {
1211         int i;
1212         struct commit *commit;
1213
1214         if (ctx->report_progress)
1215                 ctx->progress = start_delayed_progress(
1216                                         _("Loading known commits in commit graph"),
1217                                         ctx->oids.nr);
1218         for (i = 0; i < ctx->oids.nr; i++) {
1219                 display_progress(ctx->progress, i + 1);
1220                 commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
1221                 if (commit)
1222                         commit->object.flags |= REACHABLE;
1223         }
1224         stop_progress(&ctx->progress);
1225
1226         /*
1227          * As this loop runs, ctx->oids.nr may grow, but not more
1228          * than the number of missing commits in the reachable
1229          * closure.
1230          */
1231         if (ctx->report_progress)
1232                 ctx->progress = start_delayed_progress(
1233                                         _("Expanding reachable commits in commit graph"),
1234                                         0);
1235         for (i = 0; i < ctx->oids.nr; i++) {
1236                 display_progress(ctx->progress, i + 1);
1237                 commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
1238
1239                 if (!commit)
1240                         continue;
1241                 if (ctx->split) {
1242                         if (!parse_commit(commit) &&
1243                             commit->graph_pos == COMMIT_NOT_FROM_GRAPH)
1244                                 add_missing_parents(ctx, commit);
1245                 } else if (!parse_commit_no_graph(commit))
1246                         add_missing_parents(ctx, commit);
1247         }
1248         stop_progress(&ctx->progress);
1249
1250         if (ctx->report_progress)
1251                 ctx->progress = start_delayed_progress(
1252                                         _("Clearing commit marks in commit graph"),
1253                                         ctx->oids.nr);
1254         for (i = 0; i < ctx->oids.nr; i++) {
1255                 display_progress(ctx->progress, i + 1);
1256                 commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
1257
1258                 if (commit)
1259                         commit->object.flags &= ~REACHABLE;
1260         }
1261         stop_progress(&ctx->progress);
1262 }
1263
1264 static void compute_generation_numbers(struct write_commit_graph_context *ctx)
1265 {
1266         int i;
1267         struct commit_list *list = NULL;
1268
1269         if (ctx->report_progress)
1270                 ctx->progress = start_delayed_progress(
1271                                         _("Computing commit graph generation numbers"),
1272                                         ctx->commits.nr);
1273         for (i = 0; i < ctx->commits.nr; i++) {
1274                 display_progress(ctx->progress, i + 1);
1275                 if (ctx->commits.list[i]->generation != GENERATION_NUMBER_INFINITY &&
1276                     ctx->commits.list[i]->generation != GENERATION_NUMBER_ZERO)
1277                         continue;
1278
1279                 commit_list_insert(ctx->commits.list[i], &list);
1280                 while (list) {
1281                         struct commit *current = list->item;
1282                         struct commit_list *parent;
1283                         int all_parents_computed = 1;
1284                         uint32_t max_generation = 0;
1285
1286                         for (parent = current->parents; parent; parent = parent->next) {
1287                                 if (parent->item->generation == GENERATION_NUMBER_INFINITY ||
1288                                     parent->item->generation == GENERATION_NUMBER_ZERO) {
1289                                         all_parents_computed = 0;
1290                                         commit_list_insert(parent->item, &list);
1291                                         break;
1292                                 } else if (parent->item->generation > max_generation) {
1293                                         max_generation = parent->item->generation;
1294                                 }
1295                         }
1296
1297                         if (all_parents_computed) {
1298                                 current->generation = max_generation + 1;
1299                                 pop_commit(&list);
1300
1301                                 if (current->generation > GENERATION_NUMBER_MAX)
1302                                         current->generation = GENERATION_NUMBER_MAX;
1303                         }
1304                 }
1305         }
1306         stop_progress(&ctx->progress);
1307 }
1308
1309 static void compute_bloom_filters(struct write_commit_graph_context *ctx)
1310 {
1311         int i;
1312         struct progress *progress = NULL;
1313         struct commit **sorted_commits;
1314
1315         init_bloom_filters();
1316
1317         if (ctx->report_progress)
1318                 progress = start_delayed_progress(
1319                         _("Computing commit changed paths Bloom filters"),
1320                         ctx->commits.nr);
1321
1322         ALLOC_ARRAY(sorted_commits, ctx->commits.nr);
1323         COPY_ARRAY(sorted_commits, ctx->commits.list, ctx->commits.nr);
1324
1325         if (ctx->order_by_pack)
1326                 QSORT(sorted_commits, ctx->commits.nr, commit_pos_cmp);
1327         else
1328                 QSORT(sorted_commits, ctx->commits.nr, commit_gen_cmp);
1329
1330         for (i = 0; i < ctx->commits.nr; i++) {
1331                 struct commit *c = sorted_commits[i];
1332                 struct bloom_filter *filter = get_bloom_filter(ctx->r, c, 1);
1333                 ctx->total_bloom_filter_data_size += sizeof(unsigned char) * filter->len;
1334                 display_progress(progress, i + 1);
1335         }
1336
1337         free(sorted_commits);
1338         stop_progress(&progress);
1339 }
1340
1341 static int add_ref_to_list(const char *refname,
1342                            const struct object_id *oid,
1343                            int flags, void *cb_data)
1344 {
1345         struct string_list *list = (struct string_list *)cb_data;
1346
1347         string_list_append(list, oid_to_hex(oid));
1348         return 0;
1349 }
1350
1351 int write_commit_graph_reachable(struct object_directory *odb,
1352                                  enum commit_graph_write_flags flags,
1353                                  const struct split_commit_graph_opts *split_opts)
1354 {
1355         struct string_list list = STRING_LIST_INIT_DUP;
1356         int result;
1357
1358         for_each_ref(add_ref_to_list, &list);
1359         result = write_commit_graph(odb, NULL, &list,
1360                                     flags, split_opts);
1361
1362         string_list_clear(&list, 0);
1363         return result;
1364 }
1365
1366 static int fill_oids_from_packs(struct write_commit_graph_context *ctx,
1367                                 struct string_list *pack_indexes)
1368 {
1369         uint32_t i;
1370         struct strbuf progress_title = STRBUF_INIT;
1371         struct strbuf packname = STRBUF_INIT;
1372         int dirlen;
1373
1374         strbuf_addf(&packname, "%s/pack/", ctx->odb->path);
1375         dirlen = packname.len;
1376         if (ctx->report_progress) {
1377                 strbuf_addf(&progress_title,
1378                             Q_("Finding commits for commit graph in %d pack",
1379                                "Finding commits for commit graph in %d packs",
1380                                pack_indexes->nr),
1381                             pack_indexes->nr);
1382                 ctx->progress = start_delayed_progress(progress_title.buf, 0);
1383                 ctx->progress_done = 0;
1384         }
1385         for (i = 0; i < pack_indexes->nr; i++) {
1386                 struct packed_git *p;
1387                 strbuf_setlen(&packname, dirlen);
1388                 strbuf_addstr(&packname, pack_indexes->items[i].string);
1389                 p = add_packed_git(packname.buf, packname.len, 1);
1390                 if (!p) {
1391                         error(_("error adding pack %s"), packname.buf);
1392                         return -1;
1393                 }
1394                 if (open_pack_index(p)) {
1395                         error(_("error opening index for %s"), packname.buf);
1396                         return -1;
1397                 }
1398                 for_each_object_in_pack(p, add_packed_commits, ctx,
1399                                         FOR_EACH_OBJECT_PACK_ORDER);
1400                 close_pack(p);
1401                 free(p);
1402         }
1403
1404         stop_progress(&ctx->progress);
1405         strbuf_release(&progress_title);
1406         strbuf_release(&packname);
1407
1408         return 0;
1409 }
1410
1411 static int fill_oids_from_commit_hex(struct write_commit_graph_context *ctx,
1412                                      struct string_list *commit_hex)
1413 {
1414         uint32_t i;
1415         struct strbuf progress_title = STRBUF_INIT;
1416
1417         if (ctx->report_progress) {
1418                 strbuf_addf(&progress_title,
1419                             Q_("Finding commits for commit graph from %d ref",
1420                                "Finding commits for commit graph from %d refs",
1421                                commit_hex->nr),
1422                             commit_hex->nr);
1423                 ctx->progress = start_delayed_progress(
1424                                         progress_title.buf,
1425                                         commit_hex->nr);
1426         }
1427         for (i = 0; i < commit_hex->nr; i++) {
1428                 const char *end;
1429                 struct object_id oid;
1430                 struct commit *result;
1431
1432                 display_progress(ctx->progress, i + 1);
1433                 if (!parse_oid_hex(commit_hex->items[i].string, &oid, &end) &&
1434                     (result = lookup_commit_reference_gently(ctx->r, &oid, 1))) {
1435                         ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
1436                         oidcpy(&ctx->oids.list[ctx->oids.nr], &(result->object.oid));
1437                         ctx->oids.nr++;
1438                 } else if (ctx->check_oids) {
1439                         error(_("invalid commit object id: %s"),
1440                             commit_hex->items[i].string);
1441                         return -1;
1442                 }
1443         }
1444         stop_progress(&ctx->progress);
1445         strbuf_release(&progress_title);
1446
1447         return 0;
1448 }
1449
1450 static void fill_oids_from_all_packs(struct write_commit_graph_context *ctx)
1451 {
1452         if (ctx->report_progress)
1453                 ctx->progress = start_delayed_progress(
1454                         _("Finding commits for commit graph among packed objects"),
1455                         ctx->approx_nr_objects);
1456         for_each_packed_object(add_packed_commits, ctx,
1457                                FOR_EACH_OBJECT_PACK_ORDER);
1458         if (ctx->progress_done < ctx->approx_nr_objects)
1459                 display_progress(ctx->progress, ctx->approx_nr_objects);
1460         stop_progress(&ctx->progress);
1461 }
1462
1463 static uint32_t count_distinct_commits(struct write_commit_graph_context *ctx)
1464 {
1465         uint32_t i, count_distinct = 1;
1466
1467         if (ctx->report_progress)
1468                 ctx->progress = start_delayed_progress(
1469                         _("Counting distinct commits in commit graph"),
1470                         ctx->oids.nr);
1471         display_progress(ctx->progress, 0); /* TODO: Measure QSORT() progress */
1472         QSORT(ctx->oids.list, ctx->oids.nr, oid_compare);
1473
1474         for (i = 1; i < ctx->oids.nr; i++) {
1475                 display_progress(ctx->progress, i + 1);
1476                 if (!oideq(&ctx->oids.list[i - 1], &ctx->oids.list[i])) {
1477                         if (ctx->split) {
1478                                 struct commit *c = lookup_commit(ctx->r, &ctx->oids.list[i]);
1479
1480                                 if (!c || c->graph_pos != COMMIT_NOT_FROM_GRAPH)
1481                                         continue;
1482                         }
1483
1484                         count_distinct++;
1485                 }
1486         }
1487         stop_progress(&ctx->progress);
1488
1489         return count_distinct;
1490 }
1491
1492 static void copy_oids_to_commits(struct write_commit_graph_context *ctx)
1493 {
1494         uint32_t i;
1495
1496         ctx->num_extra_edges = 0;
1497         if (ctx->report_progress)
1498                 ctx->progress = start_delayed_progress(
1499                         _("Finding extra edges in commit graph"),
1500                         ctx->oids.nr);
1501         for (i = 0; i < ctx->oids.nr; i++) {
1502                 unsigned int num_parents;
1503
1504                 display_progress(ctx->progress, i + 1);
1505                 if (i > 0 && oideq(&ctx->oids.list[i - 1], &ctx->oids.list[i]))
1506                         continue;
1507
1508                 ALLOC_GROW(ctx->commits.list, ctx->commits.nr + 1, ctx->commits.alloc);
1509                 ctx->commits.list[ctx->commits.nr] = lookup_commit(ctx->r, &ctx->oids.list[i]);
1510
1511                 if (ctx->split &&
1512                     ctx->commits.list[ctx->commits.nr]->graph_pos != COMMIT_NOT_FROM_GRAPH)
1513                         continue;
1514
1515                 parse_commit_no_graph(ctx->commits.list[ctx->commits.nr]);
1516
1517                 num_parents = commit_list_count(ctx->commits.list[ctx->commits.nr]->parents);
1518                 if (num_parents > 2)
1519                         ctx->num_extra_edges += num_parents - 1;
1520
1521                 ctx->commits.nr++;
1522         }
1523         stop_progress(&ctx->progress);
1524 }
1525
1526 static int write_graph_chunk_base_1(struct hashfile *f,
1527                                     struct commit_graph *g)
1528 {
1529         int num = 0;
1530
1531         if (!g)
1532                 return 0;
1533
1534         num = write_graph_chunk_base_1(f, g->base_graph);
1535         hashwrite(f, g->oid.hash, the_hash_algo->rawsz);
1536         return num + 1;
1537 }
1538
1539 static int write_graph_chunk_base(struct hashfile *f,
1540                                   struct write_commit_graph_context *ctx)
1541 {
1542         int num = write_graph_chunk_base_1(f, ctx->new_base_graph);
1543
1544         if (num != ctx->num_commit_graphs_after - 1) {
1545                 error(_("failed to write correct number of base graph ids"));
1546                 return -1;
1547         }
1548
1549         return 0;
1550 }
1551
1552 struct chunk_info {
1553         uint32_t id;
1554         uint64_t size;
1555 };
1556
1557 static int write_commit_graph_file(struct write_commit_graph_context *ctx)
1558 {
1559         uint32_t i;
1560         int fd;
1561         struct hashfile *f;
1562         struct lock_file lk = LOCK_INIT;
1563         struct chunk_info chunks[MAX_NUM_CHUNKS + 1];
1564         const unsigned hashsz = the_hash_algo->rawsz;
1565         struct strbuf progress_title = STRBUF_INIT;
1566         int num_chunks = 3;
1567         uint64_t chunk_offset;
1568         struct object_id file_hash;
1569         struct bloom_filter_settings bloom_settings = DEFAULT_BLOOM_FILTER_SETTINGS;
1570
1571         if (!ctx->bloom_settings) {
1572                 bloom_settings.bits_per_entry = git_env_ulong("GIT_TEST_BLOOM_SETTINGS_BITS_PER_ENTRY",
1573                                                               bloom_settings.bits_per_entry);
1574                 bloom_settings.num_hashes = git_env_ulong("GIT_TEST_BLOOM_SETTINGS_NUM_HASHES",
1575                                                           bloom_settings.num_hashes);
1576                 ctx->bloom_settings = &bloom_settings;
1577         }
1578
1579         if (ctx->split) {
1580                 struct strbuf tmp_file = STRBUF_INIT;
1581
1582                 strbuf_addf(&tmp_file,
1583                             "%s/info/commit-graphs/tmp_graph_XXXXXX",
1584                             ctx->odb->path);
1585                 ctx->graph_name = strbuf_detach(&tmp_file, NULL);
1586         } else {
1587                 ctx->graph_name = get_commit_graph_filename(ctx->odb);
1588         }
1589
1590         if (safe_create_leading_directories(ctx->graph_name)) {
1591                 UNLEAK(ctx->graph_name);
1592                 error(_("unable to create leading directories of %s"),
1593                         ctx->graph_name);
1594                 return -1;
1595         }
1596
1597         if (ctx->split) {
1598                 char *lock_name = get_chain_filename(ctx->odb);
1599
1600                 hold_lock_file_for_update(&lk, lock_name, LOCK_DIE_ON_ERROR);
1601
1602                 fd = git_mkstemp_mode(ctx->graph_name, 0444);
1603                 if (fd < 0) {
1604                         error(_("unable to create '%s'"), ctx->graph_name);
1605                         return -1;
1606                 }
1607
1608                 f = hashfd(fd, ctx->graph_name);
1609         } else {
1610                 hold_lock_file_for_update(&lk, ctx->graph_name, LOCK_DIE_ON_ERROR);
1611                 fd = lk.tempfile->fd;
1612                 f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
1613         }
1614
1615         chunks[0].id = GRAPH_CHUNKID_OIDFANOUT;
1616         chunks[0].size = GRAPH_FANOUT_SIZE;
1617         chunks[1].id = GRAPH_CHUNKID_OIDLOOKUP;
1618         chunks[1].size = hashsz * ctx->commits.nr;
1619         chunks[2].id = GRAPH_CHUNKID_DATA;
1620         chunks[2].size = (hashsz + 16) * ctx->commits.nr;
1621         if (ctx->num_extra_edges) {
1622                 chunks[num_chunks].id = GRAPH_CHUNKID_EXTRAEDGES;
1623                 chunks[num_chunks].size = 4 * ctx->num_extra_edges;
1624                 num_chunks++;
1625         }
1626         if (ctx->changed_paths) {
1627                 chunks[num_chunks].id = GRAPH_CHUNKID_BLOOMINDEXES;
1628                 chunks[num_chunks].size = sizeof(uint32_t) * ctx->commits.nr;
1629                 num_chunks++;
1630                 chunks[num_chunks].id = GRAPH_CHUNKID_BLOOMDATA;
1631                 chunks[num_chunks].size = sizeof(uint32_t) * 3
1632                                           + ctx->total_bloom_filter_data_size;
1633                 num_chunks++;
1634         }
1635         if (ctx->num_commit_graphs_after > 1) {
1636                 chunks[num_chunks].id = GRAPH_CHUNKID_BASE;
1637                 chunks[num_chunks].size = hashsz * (ctx->num_commit_graphs_after - 1);
1638                 num_chunks++;
1639         }
1640
1641         chunks[num_chunks].id = 0;
1642         chunks[num_chunks].size = 0;
1643
1644         hashwrite_be32(f, GRAPH_SIGNATURE);
1645
1646         hashwrite_u8(f, GRAPH_VERSION);
1647         hashwrite_u8(f, oid_version());
1648         hashwrite_u8(f, num_chunks);
1649         hashwrite_u8(f, ctx->num_commit_graphs_after - 1);
1650
1651         chunk_offset = 8 + (num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH;
1652         for (i = 0; i <= num_chunks; i++) {
1653                 uint32_t chunk_write[3];
1654
1655                 chunk_write[0] = htonl(chunks[i].id);
1656                 chunk_write[1] = htonl(chunk_offset >> 32);
1657                 chunk_write[2] = htonl(chunk_offset & 0xffffffff);
1658                 hashwrite(f, chunk_write, 12);
1659
1660                 chunk_offset += chunks[i].size;
1661         }
1662
1663         if (ctx->report_progress) {
1664                 strbuf_addf(&progress_title,
1665                             Q_("Writing out commit graph in %d pass",
1666                                "Writing out commit graph in %d passes",
1667                                num_chunks),
1668                             num_chunks);
1669                 ctx->progress = start_delayed_progress(
1670                         progress_title.buf,
1671                         num_chunks * ctx->commits.nr);
1672         }
1673         write_graph_chunk_fanout(f, ctx);
1674         write_graph_chunk_oids(f, hashsz, ctx);
1675         write_graph_chunk_data(f, hashsz, ctx);
1676         if (ctx->num_extra_edges)
1677                 write_graph_chunk_extra_edges(f, ctx);
1678         if (ctx->changed_paths) {
1679                 write_graph_chunk_bloom_indexes(f, ctx);
1680                 write_graph_chunk_bloom_data(f, ctx);
1681         }
1682         if (ctx->num_commit_graphs_after > 1 &&
1683             write_graph_chunk_base(f, ctx)) {
1684                 return -1;
1685         }
1686         stop_progress(&ctx->progress);
1687         strbuf_release(&progress_title);
1688
1689         if (ctx->split && ctx->base_graph_name && ctx->num_commit_graphs_after > 1) {
1690                 char *new_base_hash = xstrdup(oid_to_hex(&ctx->new_base_graph->oid));
1691                 char *new_base_name = get_split_graph_filename(ctx->new_base_graph->odb, new_base_hash);
1692
1693                 free(ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 2]);
1694                 free(ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 2]);
1695                 ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 2] = new_base_name;
1696                 ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 2] = new_base_hash;
1697         }
1698
1699         close_commit_graph(ctx->r->objects);
1700         finalize_hashfile(f, file_hash.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
1701
1702         if (ctx->split) {
1703                 FILE *chainf = fdopen_lock_file(&lk, "w");
1704                 char *final_graph_name;
1705                 int result;
1706
1707                 close(fd);
1708
1709                 if (!chainf) {
1710                         error(_("unable to open commit-graph chain file"));
1711                         return -1;
1712                 }
1713
1714                 if (ctx->base_graph_name) {
1715                         const char *dest = ctx->commit_graph_filenames_after[
1716                                                 ctx->num_commit_graphs_after - 2];
1717
1718                         if (strcmp(ctx->base_graph_name, dest)) {
1719                                 result = rename(ctx->base_graph_name, dest);
1720
1721                                 if (result) {
1722                                         error(_("failed to rename base commit-graph file"));
1723                                         return -1;
1724                                 }
1725                         }
1726                 } else {
1727                         char *graph_name = get_commit_graph_filename(ctx->odb);
1728                         unlink(graph_name);
1729                 }
1730
1731                 ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 1] = xstrdup(oid_to_hex(&file_hash));
1732                 final_graph_name = get_split_graph_filename(ctx->odb,
1733                                         ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 1]);
1734                 ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 1] = final_graph_name;
1735
1736                 result = rename(ctx->graph_name, final_graph_name);
1737
1738                 for (i = 0; i < ctx->num_commit_graphs_after; i++)
1739                         fprintf(lk.tempfile->fp, "%s\n", ctx->commit_graph_hash_after[i]);
1740
1741                 if (result) {
1742                         error(_("failed to rename temporary commit-graph file"));
1743                         return -1;
1744                 }
1745         }
1746
1747         commit_lock_file(&lk);
1748
1749         return 0;
1750 }
1751
1752 static void split_graph_merge_strategy(struct write_commit_graph_context *ctx)
1753 {
1754         struct commit_graph *g;
1755         uint32_t num_commits;
1756         uint32_t i;
1757
1758         int max_commits = 0;
1759         int size_mult = 2;
1760
1761         if (ctx->split_opts) {
1762                 max_commits = ctx->split_opts->max_commits;
1763
1764                 if (ctx->split_opts->size_multiple)
1765                         size_mult = ctx->split_opts->size_multiple;
1766         }
1767
1768         g = ctx->r->objects->commit_graph;
1769         num_commits = ctx->commits.nr;
1770         ctx->num_commit_graphs_after = ctx->num_commit_graphs_before + 1;
1771
1772         while (g && (g->num_commits <= size_mult * num_commits ||
1773                     (max_commits && num_commits > max_commits))) {
1774                 if (g->odb != ctx->odb)
1775                         break;
1776
1777                 num_commits += g->num_commits;
1778                 g = g->base_graph;
1779
1780                 ctx->num_commit_graphs_after--;
1781         }
1782
1783         ctx->new_base_graph = g;
1784
1785         if (ctx->num_commit_graphs_after == 2) {
1786                 char *old_graph_name = get_commit_graph_filename(g->odb);
1787
1788                 if (!strcmp(g->filename, old_graph_name) &&
1789                     g->odb != ctx->odb) {
1790                         ctx->num_commit_graphs_after = 1;
1791                         ctx->new_base_graph = NULL;
1792                 }
1793
1794                 free(old_graph_name);
1795         }
1796
1797         ALLOC_ARRAY(ctx->commit_graph_filenames_after, ctx->num_commit_graphs_after);
1798         ALLOC_ARRAY(ctx->commit_graph_hash_after, ctx->num_commit_graphs_after);
1799
1800         for (i = 0; i < ctx->num_commit_graphs_after &&
1801                     i < ctx->num_commit_graphs_before; i++)
1802                 ctx->commit_graph_filenames_after[i] = xstrdup(ctx->commit_graph_filenames_before[i]);
1803
1804         i = ctx->num_commit_graphs_before - 1;
1805         g = ctx->r->objects->commit_graph;
1806
1807         while (g) {
1808                 if (i < ctx->num_commit_graphs_after)
1809                         ctx->commit_graph_hash_after[i] = xstrdup(oid_to_hex(&g->oid));
1810
1811                 i--;
1812                 g = g->base_graph;
1813         }
1814 }
1815
1816 static void merge_commit_graph(struct write_commit_graph_context *ctx,
1817                                struct commit_graph *g)
1818 {
1819         uint32_t i;
1820         uint32_t offset = g->num_commits_in_base;
1821
1822         ALLOC_GROW(ctx->commits.list, ctx->commits.nr + g->num_commits, ctx->commits.alloc);
1823
1824         for (i = 0; i < g->num_commits; i++) {
1825                 struct object_id oid;
1826                 struct commit *result;
1827
1828                 display_progress(ctx->progress, i + 1);
1829
1830                 load_oid_from_graph(g, i + offset, &oid);
1831
1832                 /* only add commits if they still exist in the repo */
1833                 result = lookup_commit_reference_gently(ctx->r, &oid, 1);
1834
1835                 if (result) {
1836                         ctx->commits.list[ctx->commits.nr] = result;
1837                         ctx->commits.nr++;
1838                 }
1839         }
1840 }
1841
1842 static int commit_compare(const void *_a, const void *_b)
1843 {
1844         const struct commit *a = *(const struct commit **)_a;
1845         const struct commit *b = *(const struct commit **)_b;
1846         return oidcmp(&a->object.oid, &b->object.oid);
1847 }
1848
1849 static void sort_and_scan_merged_commits(struct write_commit_graph_context *ctx)
1850 {
1851         uint32_t i;
1852
1853         if (ctx->report_progress)
1854                 ctx->progress = start_delayed_progress(
1855                                         _("Scanning merged commits"),
1856                                         ctx->commits.nr);
1857
1858         QSORT(ctx->commits.list, ctx->commits.nr, commit_compare);
1859
1860         ctx->num_extra_edges = 0;
1861         for (i = 0; i < ctx->commits.nr; i++) {
1862                 display_progress(ctx->progress, i);
1863
1864                 if (i && oideq(&ctx->commits.list[i - 1]->object.oid,
1865                           &ctx->commits.list[i]->object.oid)) {
1866                         die(_("unexpected duplicate commit id %s"),
1867                             oid_to_hex(&ctx->commits.list[i]->object.oid));
1868                 } else {
1869                         unsigned int num_parents;
1870
1871                         num_parents = commit_list_count(ctx->commits.list[i]->parents);
1872                         if (num_parents > 2)
1873                                 ctx->num_extra_edges += num_parents - 1;
1874                 }
1875         }
1876
1877         stop_progress(&ctx->progress);
1878 }
1879
1880 static void merge_commit_graphs(struct write_commit_graph_context *ctx)
1881 {
1882         struct commit_graph *g = ctx->r->objects->commit_graph;
1883         uint32_t current_graph_number = ctx->num_commit_graphs_before;
1884
1885         while (g && current_graph_number >= ctx->num_commit_graphs_after) {
1886                 current_graph_number--;
1887
1888                 if (ctx->report_progress)
1889                         ctx->progress = start_delayed_progress(_("Merging commit-graph"), 0);
1890
1891                 merge_commit_graph(ctx, g);
1892                 stop_progress(&ctx->progress);
1893
1894                 g = g->base_graph;
1895         }
1896
1897         if (g) {
1898                 ctx->new_base_graph = g;
1899                 ctx->new_num_commits_in_base = g->num_commits + g->num_commits_in_base;
1900         }
1901
1902         if (ctx->new_base_graph)
1903                 ctx->base_graph_name = xstrdup(ctx->new_base_graph->filename);
1904
1905         sort_and_scan_merged_commits(ctx);
1906 }
1907
1908 static void mark_commit_graphs(struct write_commit_graph_context *ctx)
1909 {
1910         uint32_t i;
1911         time_t now = time(NULL);
1912
1913         for (i = ctx->num_commit_graphs_after - 1; i < ctx->num_commit_graphs_before; i++) {
1914                 struct stat st;
1915                 struct utimbuf updated_time;
1916
1917                 stat(ctx->commit_graph_filenames_before[i], &st);
1918
1919                 updated_time.actime = st.st_atime;
1920                 updated_time.modtime = now;
1921                 utime(ctx->commit_graph_filenames_before[i], &updated_time);
1922         }
1923 }
1924
1925 static void expire_commit_graphs(struct write_commit_graph_context *ctx)
1926 {
1927         struct strbuf path = STRBUF_INIT;
1928         DIR *dir;
1929         struct dirent *de;
1930         size_t dirnamelen;
1931         timestamp_t expire_time = time(NULL);
1932
1933         if (ctx->split_opts && ctx->split_opts->expire_time)
1934                 expire_time -= ctx->split_opts->expire_time;
1935         if (!ctx->split) {
1936                 char *chain_file_name = get_chain_filename(ctx->odb);
1937                 unlink(chain_file_name);
1938                 free(chain_file_name);
1939                 ctx->num_commit_graphs_after = 0;
1940         }
1941
1942         strbuf_addstr(&path, ctx->odb->path);
1943         strbuf_addstr(&path, "/info/commit-graphs");
1944         dir = opendir(path.buf);
1945
1946         if (!dir)
1947                 goto out;
1948
1949         strbuf_addch(&path, '/');
1950         dirnamelen = path.len;
1951         while ((de = readdir(dir)) != NULL) {
1952                 struct stat st;
1953                 uint32_t i, found = 0;
1954
1955                 strbuf_setlen(&path, dirnamelen);
1956                 strbuf_addstr(&path, de->d_name);
1957
1958                 stat(path.buf, &st);
1959
1960                 if (st.st_mtime > expire_time)
1961                         continue;
1962                 if (path.len < 6 || strcmp(path.buf + path.len - 6, ".graph"))
1963                         continue;
1964
1965                 for (i = 0; i < ctx->num_commit_graphs_after; i++) {
1966                         if (!strcmp(ctx->commit_graph_filenames_after[i],
1967                                     path.buf)) {
1968                                 found = 1;
1969                                 break;
1970                         }
1971                 }
1972
1973                 if (!found)
1974                         unlink(path.buf);
1975         }
1976
1977 out:
1978         strbuf_release(&path);
1979 }
1980
1981 int write_commit_graph(struct object_directory *odb,
1982                        struct string_list *pack_indexes,
1983                        struct string_list *commit_hex,
1984                        enum commit_graph_write_flags flags,
1985                        const struct split_commit_graph_opts *split_opts)
1986 {
1987         struct write_commit_graph_context *ctx;
1988         uint32_t i, count_distinct = 0;
1989         int res = 0;
1990
1991         if (!commit_graph_compatible(the_repository))
1992                 return 0;
1993
1994         ctx = xcalloc(1, sizeof(struct write_commit_graph_context));
1995         ctx->r = the_repository;
1996         ctx->odb = odb;
1997         ctx->append = flags & COMMIT_GRAPH_WRITE_APPEND ? 1 : 0;
1998         ctx->report_progress = flags & COMMIT_GRAPH_WRITE_PROGRESS ? 1 : 0;
1999         ctx->split = flags & COMMIT_GRAPH_WRITE_SPLIT ? 1 : 0;
2000         ctx->check_oids = flags & COMMIT_GRAPH_WRITE_CHECK_OIDS ? 1 : 0;
2001         ctx->split_opts = split_opts;
2002         ctx->total_bloom_filter_data_size = 0;
2003
2004         if (flags & COMMIT_GRAPH_WRITE_BLOOM_FILTERS)
2005                 ctx->changed_paths = 1;
2006         if (!(flags & COMMIT_GRAPH_NO_WRITE_BLOOM_FILTERS)) {
2007                 struct commit_graph *g;
2008                 prepare_commit_graph_one(ctx->r, ctx->odb);
2009
2010                 g = ctx->r->objects->commit_graph;
2011
2012                 /* We have changed-paths already. Keep them in the next graph */
2013                 if (g && g->chunk_bloom_data) {
2014                         ctx->changed_paths = 1;
2015                         ctx->bloom_settings = g->bloom_filter_settings;
2016                 }
2017         }
2018
2019         if (ctx->split) {
2020                 struct commit_graph *g;
2021                 prepare_commit_graph(ctx->r);
2022
2023                 g = ctx->r->objects->commit_graph;
2024
2025                 while (g) {
2026                         ctx->num_commit_graphs_before++;
2027                         g = g->base_graph;
2028                 }
2029
2030                 if (ctx->num_commit_graphs_before) {
2031                         ALLOC_ARRAY(ctx->commit_graph_filenames_before, ctx->num_commit_graphs_before);
2032                         i = ctx->num_commit_graphs_before;
2033                         g = ctx->r->objects->commit_graph;
2034
2035                         while (g) {
2036                                 ctx->commit_graph_filenames_before[--i] = xstrdup(g->filename);
2037                                 g = g->base_graph;
2038                         }
2039                 }
2040         }
2041
2042         ctx->approx_nr_objects = approximate_object_count();
2043         ctx->oids.alloc = ctx->approx_nr_objects / 32;
2044
2045         if (ctx->split && split_opts && ctx->oids.alloc > split_opts->max_commits)
2046                 ctx->oids.alloc = split_opts->max_commits;
2047
2048         if (ctx->append) {
2049                 prepare_commit_graph_one(ctx->r, ctx->odb);
2050                 if (ctx->r->objects->commit_graph)
2051                         ctx->oids.alloc += ctx->r->objects->commit_graph->num_commits;
2052         }
2053
2054         if (ctx->oids.alloc < 1024)
2055                 ctx->oids.alloc = 1024;
2056         ALLOC_ARRAY(ctx->oids.list, ctx->oids.alloc);
2057
2058         if (ctx->append && ctx->r->objects->commit_graph) {
2059                 struct commit_graph *g = ctx->r->objects->commit_graph;
2060                 for (i = 0; i < g->num_commits; i++) {
2061                         const unsigned char *hash = g->chunk_oid_lookup + g->hash_len * i;
2062                         hashcpy(ctx->oids.list[ctx->oids.nr++].hash, hash);
2063                 }
2064         }
2065
2066         if (pack_indexes) {
2067                 ctx->order_by_pack = 1;
2068                 if ((res = fill_oids_from_packs(ctx, pack_indexes)))
2069                         goto cleanup;
2070         }
2071
2072         if (commit_hex) {
2073                 if ((res = fill_oids_from_commit_hex(ctx, commit_hex)))
2074                         goto cleanup;
2075         }
2076
2077         if (!pack_indexes && !commit_hex) {
2078                 ctx->order_by_pack = 1;
2079                 fill_oids_from_all_packs(ctx);
2080         }
2081
2082         close_reachable(ctx);
2083
2084         count_distinct = count_distinct_commits(ctx);
2085
2086         if (count_distinct >= GRAPH_EDGE_LAST_MASK) {
2087                 error(_("the commit graph format cannot write %d commits"), count_distinct);
2088                 res = -1;
2089                 goto cleanup;
2090         }
2091
2092         ctx->commits.alloc = count_distinct;
2093         ALLOC_ARRAY(ctx->commits.list, ctx->commits.alloc);
2094
2095         copy_oids_to_commits(ctx);
2096
2097         if (ctx->commits.nr >= GRAPH_EDGE_LAST_MASK) {
2098                 error(_("too many commits to write graph"));
2099                 res = -1;
2100                 goto cleanup;
2101         }
2102
2103         if (!ctx->commits.nr)
2104                 goto cleanup;
2105
2106         if (ctx->split) {
2107                 split_graph_merge_strategy(ctx);
2108
2109                 merge_commit_graphs(ctx);
2110         } else
2111                 ctx->num_commit_graphs_after = 1;
2112
2113         compute_generation_numbers(ctx);
2114
2115         if (ctx->changed_paths)
2116                 compute_bloom_filters(ctx);
2117
2118         res = write_commit_graph_file(ctx);
2119
2120         if (ctx->split)
2121                 mark_commit_graphs(ctx);
2122
2123         expire_commit_graphs(ctx);
2124
2125 cleanup:
2126         free(ctx->graph_name);
2127         free(ctx->commits.list);
2128         free(ctx->oids.list);
2129
2130         if (ctx->commit_graph_filenames_after) {
2131                 for (i = 0; i < ctx->num_commit_graphs_after; i++) {
2132                         free(ctx->commit_graph_filenames_after[i]);
2133                         free(ctx->commit_graph_hash_after[i]);
2134                 }
2135
2136                 for (i = 0; i < ctx->num_commit_graphs_before; i++)
2137                         free(ctx->commit_graph_filenames_before[i]);
2138
2139                 free(ctx->commit_graph_filenames_after);
2140                 free(ctx->commit_graph_filenames_before);
2141                 free(ctx->commit_graph_hash_after);
2142         }
2143
2144         free(ctx);
2145
2146         return res;
2147 }
2148
2149 #define VERIFY_COMMIT_GRAPH_ERROR_HASH 2
2150 static int verify_commit_graph_error;
2151
2152 static void graph_report(const char *fmt, ...)
2153 {
2154         va_list ap;
2155
2156         verify_commit_graph_error = 1;
2157         va_start(ap, fmt);
2158         vfprintf(stderr, fmt, ap);
2159         fprintf(stderr, "\n");
2160         va_end(ap);
2161 }
2162
2163 #define GENERATION_ZERO_EXISTS 1
2164 #define GENERATION_NUMBER_EXISTS 2
2165
2166 int verify_commit_graph(struct repository *r, struct commit_graph *g, int flags)
2167 {
2168         uint32_t i, cur_fanout_pos = 0;
2169         struct object_id prev_oid, cur_oid, checksum;
2170         int generation_zero = 0;
2171         struct hashfile *f;
2172         int devnull;
2173         struct progress *progress = NULL;
2174         int local_error = 0;
2175
2176         if (!g) {
2177                 graph_report("no commit-graph file loaded");
2178                 return 1;
2179         }
2180
2181         verify_commit_graph_error = verify_commit_graph_lite(g);
2182         if (verify_commit_graph_error)
2183                 return verify_commit_graph_error;
2184
2185         devnull = open("/dev/null", O_WRONLY);
2186         f = hashfd(devnull, NULL);
2187         hashwrite(f, g->data, g->data_len - g->hash_len);
2188         finalize_hashfile(f, checksum.hash, CSUM_CLOSE);
2189         if (!hasheq(checksum.hash, g->data + g->data_len - g->hash_len)) {
2190                 graph_report(_("the commit-graph file has incorrect checksum and is likely corrupt"));
2191                 verify_commit_graph_error = VERIFY_COMMIT_GRAPH_ERROR_HASH;
2192         }
2193
2194         for (i = 0; i < g->num_commits; i++) {
2195                 struct commit *graph_commit;
2196
2197                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
2198
2199                 if (i && oidcmp(&prev_oid, &cur_oid) >= 0)
2200                         graph_report(_("commit-graph has incorrect OID order: %s then %s"),
2201                                      oid_to_hex(&prev_oid),
2202                                      oid_to_hex(&cur_oid));
2203
2204                 oidcpy(&prev_oid, &cur_oid);
2205
2206                 while (cur_oid.hash[0] > cur_fanout_pos) {
2207                         uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
2208
2209                         if (i != fanout_value)
2210                                 graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
2211                                              cur_fanout_pos, fanout_value, i);
2212                         cur_fanout_pos++;
2213                 }
2214
2215                 graph_commit = lookup_commit(r, &cur_oid);
2216                 if (!parse_commit_in_graph_one(r, g, graph_commit))
2217                         graph_report(_("failed to parse commit %s from commit-graph"),
2218                                      oid_to_hex(&cur_oid));
2219         }
2220
2221         while (cur_fanout_pos < 256) {
2222                 uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
2223
2224                 if (g->num_commits != fanout_value)
2225                         graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
2226                                      cur_fanout_pos, fanout_value, i);
2227
2228                 cur_fanout_pos++;
2229         }
2230
2231         if (verify_commit_graph_error & ~VERIFY_COMMIT_GRAPH_ERROR_HASH)
2232                 return verify_commit_graph_error;
2233
2234         if (flags & COMMIT_GRAPH_WRITE_PROGRESS)
2235                 progress = start_progress(_("Verifying commits in commit graph"),
2236                                         g->num_commits);
2237
2238         for (i = 0; i < g->num_commits; i++) {
2239                 struct commit *graph_commit, *odb_commit;
2240                 struct commit_list *graph_parents, *odb_parents;
2241                 uint32_t max_generation = 0;
2242
2243                 display_progress(progress, i + 1);
2244                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
2245
2246                 graph_commit = lookup_commit(r, &cur_oid);
2247                 odb_commit = (struct commit *)create_object(r, &cur_oid, alloc_commit_node(r));
2248                 if (parse_commit_internal(odb_commit, 0, 0)) {
2249                         graph_report(_("failed to parse commit %s from object database for commit-graph"),
2250                                      oid_to_hex(&cur_oid));
2251                         continue;
2252                 }
2253
2254                 if (!oideq(&get_commit_tree_in_graph_one(r, g, graph_commit)->object.oid,
2255                            get_commit_tree_oid(odb_commit)))
2256                         graph_report(_("root tree OID for commit %s in commit-graph is %s != %s"),
2257                                      oid_to_hex(&cur_oid),
2258                                      oid_to_hex(get_commit_tree_oid(graph_commit)),
2259                                      oid_to_hex(get_commit_tree_oid(odb_commit)));
2260
2261                 graph_parents = graph_commit->parents;
2262                 odb_parents = odb_commit->parents;
2263
2264                 while (graph_parents) {
2265                         if (odb_parents == NULL) {
2266                                 graph_report(_("commit-graph parent list for commit %s is too long"),
2267                                              oid_to_hex(&cur_oid));
2268                                 break;
2269                         }
2270
2271                         /* parse parent in case it is in a base graph */
2272                         parse_commit_in_graph_one(r, g, graph_parents->item);
2273
2274                         if (!oideq(&graph_parents->item->object.oid, &odb_parents->item->object.oid))
2275                                 graph_report(_("commit-graph parent for %s is %s != %s"),
2276                                              oid_to_hex(&cur_oid),
2277                                              oid_to_hex(&graph_parents->item->object.oid),
2278                                              oid_to_hex(&odb_parents->item->object.oid));
2279
2280                         if (graph_parents->item->generation > max_generation)
2281                                 max_generation = graph_parents->item->generation;
2282
2283                         graph_parents = graph_parents->next;
2284                         odb_parents = odb_parents->next;
2285                 }
2286
2287                 if (odb_parents != NULL)
2288                         graph_report(_("commit-graph parent list for commit %s terminates early"),
2289                                      oid_to_hex(&cur_oid));
2290
2291                 if (!graph_commit->generation) {
2292                         if (generation_zero == GENERATION_NUMBER_EXISTS)
2293                                 graph_report(_("commit-graph has generation number zero for commit %s, but non-zero elsewhere"),
2294                                              oid_to_hex(&cur_oid));
2295                         generation_zero = GENERATION_ZERO_EXISTS;
2296                 } else if (generation_zero == GENERATION_ZERO_EXISTS)
2297                         graph_report(_("commit-graph has non-zero generation number for commit %s, but zero elsewhere"),
2298                                      oid_to_hex(&cur_oid));
2299
2300                 if (generation_zero == GENERATION_ZERO_EXISTS)
2301                         continue;
2302
2303                 /*
2304                  * If one of our parents has generation GENERATION_NUMBER_MAX, then
2305                  * our generation is also GENERATION_NUMBER_MAX. Decrement to avoid
2306                  * extra logic in the following condition.
2307                  */
2308                 if (max_generation == GENERATION_NUMBER_MAX)
2309                         max_generation--;
2310
2311                 if (graph_commit->generation != max_generation + 1)
2312                         graph_report(_("commit-graph generation for commit %s is %u != %u"),
2313                                      oid_to_hex(&cur_oid),
2314                                      graph_commit->generation,
2315                                      max_generation + 1);
2316
2317                 if (graph_commit->date != odb_commit->date)
2318                         graph_report(_("commit date for commit %s in commit-graph is %"PRItime" != %"PRItime),
2319                                      oid_to_hex(&cur_oid),
2320                                      graph_commit->date,
2321                                      odb_commit->date);
2322         }
2323         stop_progress(&progress);
2324
2325         local_error = verify_commit_graph_error;
2326
2327         if (!(flags & COMMIT_GRAPH_VERIFY_SHALLOW) && g->base_graph)
2328                 local_error |= verify_commit_graph(r, g->base_graph, flags);
2329
2330         return local_error;
2331 }
2332
2333 void free_commit_graph(struct commit_graph *g)
2334 {
2335         if (!g)
2336                 return;
2337         if (g->graph_fd >= 0) {
2338                 munmap((void *)g->data, g->data_len);
2339                 g->data = NULL;
2340                 close(g->graph_fd);
2341         }
2342         free(g->filename);
2343         free(g->bloom_filter_settings);
2344         free(g);
2345 }
2346
2347 void disable_commit_graph(struct repository *r)
2348 {
2349         r->commit_graph_disabled = 1;
2350 }