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