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