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