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