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