commit-graph.con commit l10n: Updated Vietnamese translation for v2.21 rd2 (1fc5279)
   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
  26#define GRAPH_DATA_WIDTH (the_hash_algo->rawsz + 16)
  27
  28#define GRAPH_VERSION_1 0x1
  29#define GRAPH_VERSION GRAPH_VERSION_1
  30
  31#define GRAPH_EXTRA_EDGES_NEEDED 0x80000000
  32#define GRAPH_EDGE_LAST_MASK 0x7fffffff
  33#define GRAPH_PARENT_NONE 0x70000000
  34
  35#define GRAPH_LAST_EDGE 0x80000000
  36
  37#define GRAPH_HEADER_SIZE 8
  38#define GRAPH_FANOUT_SIZE (4 * 256)
  39#define GRAPH_CHUNKLOOKUP_WIDTH 12
  40#define GRAPH_MIN_SIZE (GRAPH_HEADER_SIZE + 4 * GRAPH_CHUNKLOOKUP_WIDTH \
  41                        + GRAPH_FANOUT_SIZE + the_hash_algo->rawsz)
  42
  43char *get_commit_graph_filename(const char *obj_dir)
  44{
  45        return xstrfmt("%s/info/commit-graph", obj_dir);
  46}
  47
  48static uint8_t oid_version(void)
  49{
  50        return 1;
  51}
  52
  53static struct commit_graph *alloc_commit_graph(void)
  54{
  55        struct commit_graph *g = xcalloc(1, sizeof(*g));
  56        g->graph_fd = -1;
  57
  58        return g;
  59}
  60
  61extern int read_replace_refs;
  62
  63static int commit_graph_compatible(struct repository *r)
  64{
  65        if (!r->gitdir)
  66                return 0;
  67
  68        if (read_replace_refs) {
  69                prepare_replace_object(r);
  70                if (hashmap_get_size(&r->objects->replace_map->map))
  71                        return 0;
  72        }
  73
  74        prepare_commit_graft(r);
  75        if (r->parsed_objects && r->parsed_objects->grafts_nr)
  76                return 0;
  77        if (is_repository_shallow(r))
  78                return 0;
  79
  80        return 1;
  81}
  82
  83struct commit_graph *load_commit_graph_one(const char *graph_file)
  84{
  85        void *graph_map;
  86        size_t graph_size;
  87        struct stat st;
  88        struct commit_graph *ret;
  89        int fd = git_open(graph_file);
  90
  91        if (fd < 0)
  92                return NULL;
  93        if (fstat(fd, &st)) {
  94                close(fd);
  95                return NULL;
  96        }
  97        graph_size = xsize_t(st.st_size);
  98
  99        if (graph_size < GRAPH_MIN_SIZE) {
 100                close(fd);
 101                die(_("graph file %s is too small"), graph_file);
 102        }
 103        graph_map = xmmap(NULL, graph_size, PROT_READ, MAP_PRIVATE, fd, 0);
 104        ret = parse_commit_graph(graph_map, fd, graph_size);
 105
 106        if (!ret) {
 107                munmap(graph_map, graph_size);
 108                close(fd);
 109                exit(1);
 110        }
 111
 112        return ret;
 113}
 114
 115struct commit_graph *parse_commit_graph(void *graph_map, int fd,
 116                                        size_t graph_size)
 117{
 118        const unsigned char *data, *chunk_lookup;
 119        uint32_t i;
 120        struct commit_graph *graph;
 121        uint64_t last_chunk_offset;
 122        uint32_t last_chunk_id;
 123        uint32_t graph_signature;
 124        unsigned char graph_version, hash_version;
 125
 126        if (!graph_map)
 127                return NULL;
 128
 129        if (graph_size < GRAPH_MIN_SIZE)
 130                return NULL;
 131
 132        data = (const unsigned char *)graph_map;
 133
 134        graph_signature = get_be32(data);
 135        if (graph_signature != GRAPH_SIGNATURE) {
 136                error(_("graph signature %X does not match signature %X"),
 137                      graph_signature, GRAPH_SIGNATURE);
 138                return NULL;
 139        }
 140
 141        graph_version = *(unsigned char*)(data + 4);
 142        if (graph_version != GRAPH_VERSION) {
 143                error(_("graph version %X does not match version %X"),
 144                      graph_version, GRAPH_VERSION);
 145                return NULL;
 146        }
 147
 148        hash_version = *(unsigned char*)(data + 5);
 149        if (hash_version != oid_version()) {
 150                error(_("hash version %X does not match version %X"),
 151                      hash_version, oid_version());
 152                return NULL;
 153        }
 154
 155        graph = alloc_commit_graph();
 156
 157        graph->hash_len = the_hash_algo->rawsz;
 158        graph->num_chunks = *(unsigned char*)(data + 6);
 159        graph->graph_fd = fd;
 160        graph->data = graph_map;
 161        graph->data_len = graph_size;
 162
 163        last_chunk_id = 0;
 164        last_chunk_offset = 8;
 165        chunk_lookup = data + 8;
 166        for (i = 0; i < graph->num_chunks; i++) {
 167                uint32_t chunk_id;
 168                uint64_t chunk_offset;
 169                int chunk_repeated = 0;
 170
 171                if (data + graph_size - chunk_lookup <
 172                    GRAPH_CHUNKLOOKUP_WIDTH) {
 173                        error(_("chunk lookup table entry missing; graph file may be incomplete"));
 174                        free(graph);
 175                        return NULL;
 176                }
 177
 178                chunk_id = get_be32(chunk_lookup + 0);
 179                chunk_offset = get_be64(chunk_lookup + 4);
 180
 181                chunk_lookup += GRAPH_CHUNKLOOKUP_WIDTH;
 182
 183                if (chunk_offset > graph_size - the_hash_algo->rawsz) {
 184                        error(_("improper chunk offset %08x%08x"), (uint32_t)(chunk_offset >> 32),
 185                              (uint32_t)chunk_offset);
 186                        free(graph);
 187                        return NULL;
 188                }
 189
 190                switch (chunk_id) {
 191                case GRAPH_CHUNKID_OIDFANOUT:
 192                        if (graph->chunk_oid_fanout)
 193                                chunk_repeated = 1;
 194                        else
 195                                graph->chunk_oid_fanout = (uint32_t*)(data + chunk_offset);
 196                        break;
 197
 198                case GRAPH_CHUNKID_OIDLOOKUP:
 199                        if (graph->chunk_oid_lookup)
 200                                chunk_repeated = 1;
 201                        else
 202                                graph->chunk_oid_lookup = data + chunk_offset;
 203                        break;
 204
 205                case GRAPH_CHUNKID_DATA:
 206                        if (graph->chunk_commit_data)
 207                                chunk_repeated = 1;
 208                        else
 209                                graph->chunk_commit_data = data + chunk_offset;
 210                        break;
 211
 212                case GRAPH_CHUNKID_EXTRAEDGES:
 213                        if (graph->chunk_extra_edges)
 214                                chunk_repeated = 1;
 215                        else
 216                                graph->chunk_extra_edges = data + chunk_offset;
 217                        break;
 218                }
 219
 220                if (chunk_repeated) {
 221                        error(_("chunk id %08x appears multiple times"), chunk_id);
 222                        free(graph);
 223                        return NULL;
 224                }
 225
 226                if (last_chunk_id == GRAPH_CHUNKID_OIDLOOKUP)
 227                {
 228                        graph->num_commits = (chunk_offset - last_chunk_offset)
 229                                             / graph->hash_len;
 230                }
 231
 232                last_chunk_id = chunk_id;
 233                last_chunk_offset = chunk_offset;
 234        }
 235
 236        return graph;
 237}
 238
 239static void prepare_commit_graph_one(struct repository *r, const char *obj_dir)
 240{
 241        char *graph_name;
 242
 243        if (r->objects->commit_graph)
 244                return;
 245
 246        graph_name = get_commit_graph_filename(obj_dir);
 247        r->objects->commit_graph =
 248                load_commit_graph_one(graph_name);
 249
 250        FREE_AND_NULL(graph_name);
 251}
 252
 253/*
 254 * Return 1 if commit_graph is non-NULL, and 0 otherwise.
 255 *
 256 * On the first invocation, this function attemps to load the commit
 257 * graph if the_repository is configured to have one.
 258 */
 259static int prepare_commit_graph(struct repository *r)
 260{
 261        struct object_directory *odb;
 262        int config_value;
 263
 264        if (r->objects->commit_graph_attempted)
 265                return !!r->objects->commit_graph;
 266        r->objects->commit_graph_attempted = 1;
 267
 268        if (!git_env_bool(GIT_TEST_COMMIT_GRAPH, 0) &&
 269            (repo_config_get_bool(r, "core.commitgraph", &config_value) ||
 270            !config_value))
 271                /*
 272                 * This repository is not configured to use commit graphs, so
 273                 * do not load one. (But report commit_graph_attempted anyway
 274                 * so that commit graph loading is not attempted again for this
 275                 * repository.)
 276                 */
 277                return 0;
 278
 279        if (!commit_graph_compatible(r))
 280                return 0;
 281
 282        prepare_alt_odb(r);
 283        for (odb = r->objects->odb;
 284             !r->objects->commit_graph && odb;
 285             odb = odb->next)
 286                prepare_commit_graph_one(r, odb->path);
 287        return !!r->objects->commit_graph;
 288}
 289
 290int generation_numbers_enabled(struct repository *r)
 291{
 292        uint32_t first_generation;
 293        struct commit_graph *g;
 294        if (!prepare_commit_graph(r))
 295               return 0;
 296
 297        g = r->objects->commit_graph;
 298
 299        if (!g->num_commits)
 300                return 0;
 301
 302        first_generation = get_be32(g->chunk_commit_data +
 303                                    g->hash_len + 8) >> 2;
 304
 305        return !!first_generation;
 306}
 307
 308void close_commit_graph(struct repository *r)
 309{
 310        free_commit_graph(r->objects->commit_graph);
 311        r->objects->commit_graph = NULL;
 312}
 313
 314static int bsearch_graph(struct commit_graph *g, struct object_id *oid, uint32_t *pos)
 315{
 316        return bsearch_hash(oid->hash, g->chunk_oid_fanout,
 317                            g->chunk_oid_lookup, g->hash_len, pos);
 318}
 319
 320static struct commit_list **insert_parent_or_die(struct repository *r,
 321                                                 struct commit_graph *g,
 322                                                 uint64_t pos,
 323                                                 struct commit_list **pptr)
 324{
 325        struct commit *c;
 326        struct object_id oid;
 327
 328        if (pos >= g->num_commits)
 329                die("invalid parent position %"PRIu64, pos);
 330
 331        hashcpy(oid.hash, g->chunk_oid_lookup + g->hash_len * pos);
 332        c = lookup_commit(r, &oid);
 333        if (!c)
 334                die(_("could not find commit %s"), oid_to_hex(&oid));
 335        c->graph_pos = pos;
 336        return &commit_list_insert(c, pptr)->next;
 337}
 338
 339static void fill_commit_graph_info(struct commit *item, struct commit_graph *g, uint32_t pos)
 340{
 341        const unsigned char *commit_data = g->chunk_commit_data + GRAPH_DATA_WIDTH * pos;
 342        item->graph_pos = pos;
 343        item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
 344}
 345
 346static int fill_commit_in_graph(struct repository *r,
 347                                struct commit *item,
 348                                struct commit_graph *g, uint32_t pos)
 349{
 350        uint32_t edge_value;
 351        uint32_t *parent_data_ptr;
 352        uint64_t date_low, date_high;
 353        struct commit_list **pptr;
 354        const unsigned char *commit_data = g->chunk_commit_data + (g->hash_len + 16) * pos;
 355
 356        item->object.parsed = 1;
 357        item->graph_pos = pos;
 358
 359        item->maybe_tree = NULL;
 360
 361        date_high = get_be32(commit_data + g->hash_len + 8) & 0x3;
 362        date_low = get_be32(commit_data + g->hash_len + 12);
 363        item->date = (timestamp_t)((date_high << 32) | date_low);
 364
 365        item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
 366
 367        pptr = &item->parents;
 368
 369        edge_value = get_be32(commit_data + g->hash_len);
 370        if (edge_value == GRAPH_PARENT_NONE)
 371                return 1;
 372        pptr = insert_parent_or_die(r, g, edge_value, pptr);
 373
 374        edge_value = get_be32(commit_data + g->hash_len + 4);
 375        if (edge_value == GRAPH_PARENT_NONE)
 376                return 1;
 377        if (!(edge_value & GRAPH_EXTRA_EDGES_NEEDED)) {
 378                pptr = insert_parent_or_die(r, g, edge_value, pptr);
 379                return 1;
 380        }
 381
 382        parent_data_ptr = (uint32_t*)(g->chunk_extra_edges +
 383                          4 * (uint64_t)(edge_value & GRAPH_EDGE_LAST_MASK));
 384        do {
 385                edge_value = get_be32(parent_data_ptr);
 386                pptr = insert_parent_or_die(r, g,
 387                                            edge_value & GRAPH_EDGE_LAST_MASK,
 388                                            pptr);
 389                parent_data_ptr++;
 390        } while (!(edge_value & GRAPH_LAST_EDGE));
 391
 392        return 1;
 393}
 394
 395static int find_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t *pos)
 396{
 397        if (item->graph_pos != COMMIT_NOT_FROM_GRAPH) {
 398                *pos = item->graph_pos;
 399                return 1;
 400        } else {
 401                return bsearch_graph(g, &(item->object.oid), pos);
 402        }
 403}
 404
 405static int parse_commit_in_graph_one(struct repository *r,
 406                                     struct commit_graph *g,
 407                                     struct commit *item)
 408{
 409        uint32_t pos;
 410
 411        if (item->object.parsed)
 412                return 1;
 413
 414        if (find_commit_in_graph(item, g, &pos))
 415                return fill_commit_in_graph(r, item, g, pos);
 416
 417        return 0;
 418}
 419
 420int parse_commit_in_graph(struct repository *r, struct commit *item)
 421{
 422        if (!prepare_commit_graph(r))
 423                return 0;
 424        return parse_commit_in_graph_one(r, r->objects->commit_graph, item);
 425}
 426
 427void load_commit_graph_info(struct repository *r, struct commit *item)
 428{
 429        uint32_t pos;
 430        if (!prepare_commit_graph(r))
 431                return;
 432        if (find_commit_in_graph(item, r->objects->commit_graph, &pos))
 433                fill_commit_graph_info(item, r->objects->commit_graph, pos);
 434}
 435
 436static struct tree *load_tree_for_commit(struct repository *r,
 437                                         struct commit_graph *g,
 438                                         struct commit *c)
 439{
 440        struct object_id oid;
 441        const unsigned char *commit_data = g->chunk_commit_data +
 442                                           GRAPH_DATA_WIDTH * (c->graph_pos);
 443
 444        hashcpy(oid.hash, commit_data);
 445        c->maybe_tree = lookup_tree(r, &oid);
 446
 447        return c->maybe_tree;
 448}
 449
 450static struct tree *get_commit_tree_in_graph_one(struct repository *r,
 451                                                 struct commit_graph *g,
 452                                                 const struct commit *c)
 453{
 454        if (c->maybe_tree)
 455                return c->maybe_tree;
 456        if (c->graph_pos == COMMIT_NOT_FROM_GRAPH)
 457                BUG("get_commit_tree_in_graph_one called from non-commit-graph commit");
 458
 459        return load_tree_for_commit(r, g, (struct commit *)c);
 460}
 461
 462struct tree *get_commit_tree_in_graph(struct repository *r, const struct commit *c)
 463{
 464        return get_commit_tree_in_graph_one(r, r->objects->commit_graph, c);
 465}
 466
 467static void write_graph_chunk_fanout(struct hashfile *f,
 468                                     struct commit **commits,
 469                                     int nr_commits,
 470                                     struct progress *progress,
 471                                     uint64_t *progress_cnt)
 472{
 473        int i, count = 0;
 474        struct commit **list = commits;
 475
 476        /*
 477         * Write the first-level table (the list is sorted,
 478         * but we use a 256-entry lookup to be able to avoid
 479         * having to do eight extra binary search iterations).
 480         */
 481        for (i = 0; i < 256; i++) {
 482                while (count < nr_commits) {
 483                        if ((*list)->object.oid.hash[0] != i)
 484                                break;
 485                        display_progress(progress, ++*progress_cnt);
 486                        count++;
 487                        list++;
 488                }
 489
 490                hashwrite_be32(f, count);
 491        }
 492}
 493
 494static void write_graph_chunk_oids(struct hashfile *f, int hash_len,
 495                                   struct commit **commits, int nr_commits,
 496                                   struct progress *progress,
 497                                   uint64_t *progress_cnt)
 498{
 499        struct commit **list = commits;
 500        int count;
 501        for (count = 0; count < nr_commits; count++, list++) {
 502                display_progress(progress, ++*progress_cnt);
 503                hashwrite(f, (*list)->object.oid.hash, (int)hash_len);
 504        }
 505}
 506
 507static const unsigned char *commit_to_sha1(size_t index, void *table)
 508{
 509        struct commit **commits = table;
 510        return commits[index]->object.oid.hash;
 511}
 512
 513static void write_graph_chunk_data(struct hashfile *f, int hash_len,
 514                                   struct commit **commits, int nr_commits,
 515                                   struct progress *progress,
 516                                   uint64_t *progress_cnt)
 517{
 518        struct commit **list = commits;
 519        struct commit **last = commits + nr_commits;
 520        uint32_t num_extra_edges = 0;
 521
 522        while (list < last) {
 523                struct commit_list *parent;
 524                int edge_value;
 525                uint32_t packedDate[2];
 526                display_progress(progress, ++*progress_cnt);
 527
 528                parse_commit(*list);
 529                hashwrite(f, get_commit_tree_oid(*list)->hash, hash_len);
 530
 531                parent = (*list)->parents;
 532
 533                if (!parent)
 534                        edge_value = GRAPH_PARENT_NONE;
 535                else {
 536                        edge_value = sha1_pos(parent->item->object.oid.hash,
 537                                              commits,
 538                                              nr_commits,
 539                                              commit_to_sha1);
 540
 541                        if (edge_value < 0)
 542                                BUG("missing parent %s for commit %s",
 543                                    oid_to_hex(&parent->item->object.oid),
 544                                    oid_to_hex(&(*list)->object.oid));
 545                }
 546
 547                hashwrite_be32(f, edge_value);
 548
 549                if (parent)
 550                        parent = parent->next;
 551
 552                if (!parent)
 553                        edge_value = GRAPH_PARENT_NONE;
 554                else if (parent->next)
 555                        edge_value = GRAPH_EXTRA_EDGES_NEEDED | num_extra_edges;
 556                else {
 557                        edge_value = sha1_pos(parent->item->object.oid.hash,
 558                                              commits,
 559                                              nr_commits,
 560                                              commit_to_sha1);
 561                        if (edge_value < 0)
 562                                BUG("missing parent %s for commit %s",
 563                                    oid_to_hex(&parent->item->object.oid),
 564                                    oid_to_hex(&(*list)->object.oid));
 565                }
 566
 567                hashwrite_be32(f, edge_value);
 568
 569                if (edge_value & GRAPH_EXTRA_EDGES_NEEDED) {
 570                        do {
 571                                num_extra_edges++;
 572                                parent = parent->next;
 573                        } while (parent);
 574                }
 575
 576                if (sizeof((*list)->date) > 4)
 577                        packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
 578                else
 579                        packedDate[0] = 0;
 580
 581                packedDate[0] |= htonl((*list)->generation << 2);
 582
 583                packedDate[1] = htonl((*list)->date);
 584                hashwrite(f, packedDate, 8);
 585
 586                list++;
 587        }
 588}
 589
 590static void write_graph_chunk_extra_edges(struct hashfile *f,
 591                                          struct commit **commits,
 592                                          int nr_commits,
 593                                          struct progress *progress,
 594                                          uint64_t *progress_cnt)
 595{
 596        struct commit **list = commits;
 597        struct commit **last = commits + nr_commits;
 598        struct commit_list *parent;
 599
 600        while (list < last) {
 601                int num_parents = 0;
 602
 603                display_progress(progress, ++*progress_cnt);
 604
 605                for (parent = (*list)->parents; num_parents < 3 && parent;
 606                     parent = parent->next)
 607                        num_parents++;
 608
 609                if (num_parents <= 2) {
 610                        list++;
 611                        continue;
 612                }
 613
 614                /* Since num_parents > 2, this initializer is safe. */
 615                for (parent = (*list)->parents->next; parent; parent = parent->next) {
 616                        int edge_value = sha1_pos(parent->item->object.oid.hash,
 617                                                  commits,
 618                                                  nr_commits,
 619                                                  commit_to_sha1);
 620
 621                        if (edge_value < 0)
 622                                BUG("missing parent %s for commit %s",
 623                                    oid_to_hex(&parent->item->object.oid),
 624                                    oid_to_hex(&(*list)->object.oid));
 625                        else if (!parent->next)
 626                                edge_value |= GRAPH_LAST_EDGE;
 627
 628                        hashwrite_be32(f, edge_value);
 629                }
 630
 631                list++;
 632        }
 633}
 634
 635static int commit_compare(const void *_a, const void *_b)
 636{
 637        const struct object_id *a = (const struct object_id *)_a;
 638        const struct object_id *b = (const struct object_id *)_b;
 639        return oidcmp(a, b);
 640}
 641
 642struct packed_commit_list {
 643        struct commit **list;
 644        int nr;
 645        int alloc;
 646};
 647
 648struct packed_oid_list {
 649        struct object_id *list;
 650        int nr;
 651        int alloc;
 652        struct progress *progress;
 653        int progress_done;
 654};
 655
 656static int add_packed_commits(const struct object_id *oid,
 657                              struct packed_git *pack,
 658                              uint32_t pos,
 659                              void *data)
 660{
 661        struct packed_oid_list *list = (struct packed_oid_list*)data;
 662        enum object_type type;
 663        off_t offset = nth_packed_object_offset(pack, pos);
 664        struct object_info oi = OBJECT_INFO_INIT;
 665
 666        if (list->progress)
 667                display_progress(list->progress, ++list->progress_done);
 668
 669        oi.typep = &type;
 670        if (packed_object_info(the_repository, pack, offset, &oi) < 0)
 671                die(_("unable to get type of object %s"), oid_to_hex(oid));
 672
 673        if (type != OBJ_COMMIT)
 674                return 0;
 675
 676        ALLOC_GROW(list->list, list->nr + 1, list->alloc);
 677        oidcpy(&(list->list[list->nr]), oid);
 678        list->nr++;
 679
 680        return 0;
 681}
 682
 683static void add_missing_parents(struct packed_oid_list *oids, struct commit *commit)
 684{
 685        struct commit_list *parent;
 686        for (parent = commit->parents; parent; parent = parent->next) {
 687                if (!(parent->item->object.flags & UNINTERESTING)) {
 688                        ALLOC_GROW(oids->list, oids->nr + 1, oids->alloc);
 689                        oidcpy(&oids->list[oids->nr], &(parent->item->object.oid));
 690                        oids->nr++;
 691                        parent->item->object.flags |= UNINTERESTING;
 692                }
 693        }
 694}
 695
 696static void close_reachable(struct packed_oid_list *oids, int report_progress)
 697{
 698        int i;
 699        struct commit *commit;
 700        struct progress *progress = NULL;
 701
 702        if (report_progress)
 703                progress = start_delayed_progress(
 704                        _("Loading known commits in commit graph"), oids->nr);
 705        for (i = 0; i < oids->nr; i++) {
 706                display_progress(progress, i + 1);
 707                commit = lookup_commit(the_repository, &oids->list[i]);
 708                if (commit)
 709                        commit->object.flags |= UNINTERESTING;
 710        }
 711        stop_progress(&progress);
 712
 713        /*
 714         * As this loop runs, oids->nr may grow, but not more
 715         * than the number of missing commits in the reachable
 716         * closure.
 717         */
 718        if (report_progress)
 719                progress = start_delayed_progress(
 720                        _("Expanding reachable commits in commit graph"), oids->nr);
 721        for (i = 0; i < oids->nr; i++) {
 722                display_progress(progress, i + 1);
 723                commit = lookup_commit(the_repository, &oids->list[i]);
 724
 725                if (commit && !parse_commit(commit))
 726                        add_missing_parents(oids, commit);
 727        }
 728        stop_progress(&progress);
 729
 730        if (report_progress)
 731                progress = start_delayed_progress(
 732                        _("Clearing commit marks in commit graph"), oids->nr);
 733        for (i = 0; i < oids->nr; i++) {
 734                display_progress(progress, i + 1);
 735                commit = lookup_commit(the_repository, &oids->list[i]);
 736
 737                if (commit)
 738                        commit->object.flags &= ~UNINTERESTING;
 739        }
 740        stop_progress(&progress);
 741}
 742
 743static void compute_generation_numbers(struct packed_commit_list* commits,
 744                                       int report_progress)
 745{
 746        int i;
 747        struct commit_list *list = NULL;
 748        struct progress *progress = NULL;
 749
 750        if (report_progress)
 751                progress = start_progress(
 752                        _("Computing commit graph generation numbers"),
 753                        commits->nr);
 754        for (i = 0; i < commits->nr; i++) {
 755                display_progress(progress, i + 1);
 756                if (commits->list[i]->generation != GENERATION_NUMBER_INFINITY &&
 757                    commits->list[i]->generation != GENERATION_NUMBER_ZERO)
 758                        continue;
 759
 760                commit_list_insert(commits->list[i], &list);
 761                while (list) {
 762                        struct commit *current = list->item;
 763                        struct commit_list *parent;
 764                        int all_parents_computed = 1;
 765                        uint32_t max_generation = 0;
 766
 767                        for (parent = current->parents; parent; parent = parent->next) {
 768                                if (parent->item->generation == GENERATION_NUMBER_INFINITY ||
 769                                    parent->item->generation == GENERATION_NUMBER_ZERO) {
 770                                        all_parents_computed = 0;
 771                                        commit_list_insert(parent->item, &list);
 772                                        break;
 773                                } else if (parent->item->generation > max_generation) {
 774                                        max_generation = parent->item->generation;
 775                                }
 776                        }
 777
 778                        if (all_parents_computed) {
 779                                current->generation = max_generation + 1;
 780                                pop_commit(&list);
 781
 782                                if (current->generation > GENERATION_NUMBER_MAX)
 783                                        current->generation = GENERATION_NUMBER_MAX;
 784                        }
 785                }
 786        }
 787        stop_progress(&progress);
 788}
 789
 790static int add_ref_to_list(const char *refname,
 791                           const struct object_id *oid,
 792                           int flags, void *cb_data)
 793{
 794        struct string_list *list = (struct string_list *)cb_data;
 795
 796        string_list_append(list, oid_to_hex(oid));
 797        return 0;
 798}
 799
 800void write_commit_graph_reachable(const char *obj_dir, int append,
 801                                  int report_progress)
 802{
 803        struct string_list list = STRING_LIST_INIT_DUP;
 804
 805        for_each_ref(add_ref_to_list, &list);
 806        write_commit_graph(obj_dir, NULL, &list, append, report_progress);
 807
 808        string_list_clear(&list, 0);
 809}
 810
 811void write_commit_graph(const char *obj_dir,
 812                        struct string_list *pack_indexes,
 813                        struct string_list *commit_hex,
 814                        int append, int report_progress)
 815{
 816        struct packed_oid_list oids;
 817        struct packed_commit_list commits;
 818        struct hashfile *f;
 819        uint32_t i, count_distinct = 0;
 820        char *graph_name;
 821        struct lock_file lk = LOCK_INIT;
 822        uint32_t chunk_ids[5];
 823        uint64_t chunk_offsets[5];
 824        int num_chunks;
 825        int num_extra_edges;
 826        struct commit_list *parent;
 827        struct progress *progress = NULL;
 828        const unsigned hashsz = the_hash_algo->rawsz;
 829        uint64_t progress_cnt = 0;
 830        struct strbuf progress_title = STRBUF_INIT;
 831        unsigned long approx_nr_objects;
 832
 833        if (!commit_graph_compatible(the_repository))
 834                return;
 835
 836        oids.nr = 0;
 837        approx_nr_objects = approximate_object_count();
 838        oids.alloc = approx_nr_objects / 32;
 839        oids.progress = NULL;
 840        oids.progress_done = 0;
 841
 842        if (append) {
 843                prepare_commit_graph_one(the_repository, obj_dir);
 844                if (the_repository->objects->commit_graph)
 845                        oids.alloc += the_repository->objects->commit_graph->num_commits;
 846        }
 847
 848        if (oids.alloc < 1024)
 849                oids.alloc = 1024;
 850        ALLOC_ARRAY(oids.list, oids.alloc);
 851
 852        if (append && the_repository->objects->commit_graph) {
 853                struct commit_graph *commit_graph =
 854                        the_repository->objects->commit_graph;
 855                for (i = 0; i < commit_graph->num_commits; i++) {
 856                        const unsigned char *hash = commit_graph->chunk_oid_lookup +
 857                                commit_graph->hash_len * i;
 858                        hashcpy(oids.list[oids.nr++].hash, hash);
 859                }
 860        }
 861
 862        if (pack_indexes) {
 863                struct strbuf packname = STRBUF_INIT;
 864                int dirlen;
 865                strbuf_addf(&packname, "%s/pack/", obj_dir);
 866                dirlen = packname.len;
 867                if (report_progress) {
 868                        strbuf_addf(&progress_title,
 869                                    Q_("Finding commits for commit graph in %d pack",
 870                                       "Finding commits for commit graph in %d packs",
 871                                       pack_indexes->nr),
 872                                    pack_indexes->nr);
 873                        oids.progress = start_delayed_progress(progress_title.buf, 0);
 874                        oids.progress_done = 0;
 875                }
 876                for (i = 0; i < pack_indexes->nr; i++) {
 877                        struct packed_git *p;
 878                        strbuf_setlen(&packname, dirlen);
 879                        strbuf_addstr(&packname, pack_indexes->items[i].string);
 880                        p = add_packed_git(packname.buf, packname.len, 1);
 881                        if (!p)
 882                                die(_("error adding pack %s"), packname.buf);
 883                        if (open_pack_index(p))
 884                                die(_("error opening index for %s"), packname.buf);
 885                        for_each_object_in_pack(p, add_packed_commits, &oids,
 886                                                FOR_EACH_OBJECT_PACK_ORDER);
 887                        close_pack(p);
 888                        free(p);
 889                }
 890                stop_progress(&oids.progress);
 891                strbuf_reset(&progress_title);
 892                strbuf_release(&packname);
 893        }
 894
 895        if (commit_hex) {
 896                if (report_progress) {
 897                        strbuf_addf(&progress_title,
 898                                    Q_("Finding commits for commit graph from %d ref",
 899                                       "Finding commits for commit graph from %d refs",
 900                                       commit_hex->nr),
 901                                    commit_hex->nr);
 902                        progress = start_delayed_progress(progress_title.buf,
 903                                                          commit_hex->nr);
 904                }
 905                for (i = 0; i < commit_hex->nr; i++) {
 906                        const char *end;
 907                        struct object_id oid;
 908                        struct commit *result;
 909
 910                        display_progress(progress, i + 1);
 911                        if (commit_hex->items[i].string &&
 912                            parse_oid_hex(commit_hex->items[i].string, &oid, &end))
 913                                continue;
 914
 915                        result = lookup_commit_reference_gently(the_repository, &oid, 1);
 916
 917                        if (result) {
 918                                ALLOC_GROW(oids.list, oids.nr + 1, oids.alloc);
 919                                oidcpy(&oids.list[oids.nr], &(result->object.oid));
 920                                oids.nr++;
 921                        }
 922                }
 923                stop_progress(&progress);
 924                strbuf_reset(&progress_title);
 925        }
 926
 927        if (!pack_indexes && !commit_hex) {
 928                if (report_progress)
 929                        oids.progress = start_delayed_progress(
 930                                _("Finding commits for commit graph among packed objects"),
 931                                approx_nr_objects);
 932                for_each_packed_object(add_packed_commits, &oids,
 933                                       FOR_EACH_OBJECT_PACK_ORDER);
 934                if (oids.progress_done < approx_nr_objects)
 935                        display_progress(oids.progress, approx_nr_objects);
 936                stop_progress(&oids.progress);
 937        }
 938
 939        close_reachable(&oids, report_progress);
 940
 941        if (report_progress)
 942                progress = start_delayed_progress(
 943                        _("Counting distinct commits in commit graph"),
 944                        oids.nr);
 945        display_progress(progress, 0); /* TODO: Measure QSORT() progress */
 946        QSORT(oids.list, oids.nr, commit_compare);
 947        count_distinct = 1;
 948        for (i = 1; i < oids.nr; i++) {
 949                display_progress(progress, i + 1);
 950                if (!oideq(&oids.list[i - 1], &oids.list[i]))
 951                        count_distinct++;
 952        }
 953        stop_progress(&progress);
 954
 955        if (count_distinct >= GRAPH_EDGE_LAST_MASK)
 956                die(_("the commit graph format cannot write %d commits"), count_distinct);
 957
 958        commits.nr = 0;
 959        commits.alloc = count_distinct;
 960        ALLOC_ARRAY(commits.list, commits.alloc);
 961
 962        num_extra_edges = 0;
 963        if (report_progress)
 964                progress = start_delayed_progress(
 965                        _("Finding extra edges in commit graph"),
 966                        oids.nr);
 967        for (i = 0; i < oids.nr; i++) {
 968                int num_parents = 0;
 969                display_progress(progress, i + 1);
 970                if (i > 0 && oideq(&oids.list[i - 1], &oids.list[i]))
 971                        continue;
 972
 973                commits.list[commits.nr] = lookup_commit(the_repository, &oids.list[i]);
 974                parse_commit(commits.list[commits.nr]);
 975
 976                for (parent = commits.list[commits.nr]->parents;
 977                     parent; parent = parent->next)
 978                        num_parents++;
 979
 980                if (num_parents > 2)
 981                        num_extra_edges += num_parents - 1;
 982
 983                commits.nr++;
 984        }
 985        num_chunks = num_extra_edges ? 4 : 3;
 986        stop_progress(&progress);
 987
 988        if (commits.nr >= GRAPH_EDGE_LAST_MASK)
 989                die(_("too many commits to write graph"));
 990
 991        compute_generation_numbers(&commits, report_progress);
 992
 993        graph_name = get_commit_graph_filename(obj_dir);
 994        if (safe_create_leading_directories(graph_name)) {
 995                UNLEAK(graph_name);
 996                die_errno(_("unable to create leading directories of %s"),
 997                          graph_name);
 998        }
 999
1000        hold_lock_file_for_update(&lk, graph_name, LOCK_DIE_ON_ERROR);
1001        f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
1002
1003        hashwrite_be32(f, GRAPH_SIGNATURE);
1004
1005        hashwrite_u8(f, GRAPH_VERSION);
1006        hashwrite_u8(f, oid_version());
1007        hashwrite_u8(f, num_chunks);
1008        hashwrite_u8(f, 0); /* unused padding byte */
1009
1010        chunk_ids[0] = GRAPH_CHUNKID_OIDFANOUT;
1011        chunk_ids[1] = GRAPH_CHUNKID_OIDLOOKUP;
1012        chunk_ids[2] = GRAPH_CHUNKID_DATA;
1013        if (num_extra_edges)
1014                chunk_ids[3] = GRAPH_CHUNKID_EXTRAEDGES;
1015        else
1016                chunk_ids[3] = 0;
1017        chunk_ids[4] = 0;
1018
1019        chunk_offsets[0] = 8 + (num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH;
1020        chunk_offsets[1] = chunk_offsets[0] + GRAPH_FANOUT_SIZE;
1021        chunk_offsets[2] = chunk_offsets[1] + hashsz * commits.nr;
1022        chunk_offsets[3] = chunk_offsets[2] + (hashsz + 16) * commits.nr;
1023        chunk_offsets[4] = chunk_offsets[3] + 4 * num_extra_edges;
1024
1025        for (i = 0; i <= num_chunks; i++) {
1026                uint32_t chunk_write[3];
1027
1028                chunk_write[0] = htonl(chunk_ids[i]);
1029                chunk_write[1] = htonl(chunk_offsets[i] >> 32);
1030                chunk_write[2] = htonl(chunk_offsets[i] & 0xffffffff);
1031                hashwrite(f, chunk_write, 12);
1032        }
1033
1034        if (report_progress) {
1035                strbuf_addf(&progress_title,
1036                            Q_("Writing out commit graph in %d pass",
1037                               "Writing out commit graph in %d passes",
1038                               num_chunks),
1039                            num_chunks);
1040                progress = start_delayed_progress(
1041                        progress_title.buf,
1042                        num_chunks * commits.nr);
1043        }
1044        write_graph_chunk_fanout(f, commits.list, commits.nr, progress, &progress_cnt);
1045        write_graph_chunk_oids(f, hashsz, commits.list, commits.nr, progress, &progress_cnt);
1046        write_graph_chunk_data(f, hashsz, commits.list, commits.nr, progress, &progress_cnt);
1047        if (num_extra_edges)
1048                write_graph_chunk_extra_edges(f, commits.list, commits.nr, progress, &progress_cnt);
1049        stop_progress(&progress);
1050        strbuf_release(&progress_title);
1051
1052        close_commit_graph(the_repository);
1053        finalize_hashfile(f, NULL, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
1054        commit_lock_file(&lk);
1055
1056        free(graph_name);
1057        free(commits.list);
1058        free(oids.list);
1059}
1060
1061#define VERIFY_COMMIT_GRAPH_ERROR_HASH 2
1062static int verify_commit_graph_error;
1063
1064static void graph_report(const char *fmt, ...)
1065{
1066        va_list ap;
1067
1068        verify_commit_graph_error = 1;
1069        va_start(ap, fmt);
1070        vfprintf(stderr, fmt, ap);
1071        fprintf(stderr, "\n");
1072        va_end(ap);
1073}
1074
1075#define GENERATION_ZERO_EXISTS 1
1076#define GENERATION_NUMBER_EXISTS 2
1077
1078int verify_commit_graph(struct repository *r, struct commit_graph *g)
1079{
1080        uint32_t i, cur_fanout_pos = 0;
1081        struct object_id prev_oid, cur_oid, checksum;
1082        int generation_zero = 0;
1083        struct hashfile *f;
1084        int devnull;
1085        struct progress *progress = NULL;
1086
1087        if (!g) {
1088                graph_report("no commit-graph file loaded");
1089                return 1;
1090        }
1091
1092        verify_commit_graph_error = 0;
1093
1094        if (!g->chunk_oid_fanout)
1095                graph_report("commit-graph is missing the OID Fanout chunk");
1096        if (!g->chunk_oid_lookup)
1097                graph_report("commit-graph is missing the OID Lookup chunk");
1098        if (!g->chunk_commit_data)
1099                graph_report("commit-graph is missing the Commit Data chunk");
1100
1101        if (verify_commit_graph_error)
1102                return verify_commit_graph_error;
1103
1104        devnull = open("/dev/null", O_WRONLY);
1105        f = hashfd(devnull, NULL);
1106        hashwrite(f, g->data, g->data_len - g->hash_len);
1107        finalize_hashfile(f, checksum.hash, CSUM_CLOSE);
1108        if (!hasheq(checksum.hash, g->data + g->data_len - g->hash_len)) {
1109                graph_report(_("the commit-graph file has incorrect checksum and is likely corrupt"));
1110                verify_commit_graph_error = VERIFY_COMMIT_GRAPH_ERROR_HASH;
1111        }
1112
1113        for (i = 0; i < g->num_commits; i++) {
1114                struct commit *graph_commit;
1115
1116                hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1117
1118                if (i && oidcmp(&prev_oid, &cur_oid) >= 0)
1119                        graph_report("commit-graph has incorrect OID order: %s then %s",
1120                                     oid_to_hex(&prev_oid),
1121                                     oid_to_hex(&cur_oid));
1122
1123                oidcpy(&prev_oid, &cur_oid);
1124
1125                while (cur_oid.hash[0] > cur_fanout_pos) {
1126                        uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1127
1128                        if (i != fanout_value)
1129                                graph_report("commit-graph has incorrect fanout value: fanout[%d] = %u != %u",
1130                                             cur_fanout_pos, fanout_value, i);
1131                        cur_fanout_pos++;
1132                }
1133
1134                graph_commit = lookup_commit(r, &cur_oid);
1135                if (!parse_commit_in_graph_one(r, g, graph_commit))
1136                        graph_report("failed to parse %s from commit-graph",
1137                                     oid_to_hex(&cur_oid));
1138        }
1139
1140        while (cur_fanout_pos < 256) {
1141                uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1142
1143                if (g->num_commits != fanout_value)
1144                        graph_report("commit-graph has incorrect fanout value: fanout[%d] = %u != %u",
1145                                     cur_fanout_pos, fanout_value, i);
1146
1147                cur_fanout_pos++;
1148        }
1149
1150        if (verify_commit_graph_error & ~VERIFY_COMMIT_GRAPH_ERROR_HASH)
1151                return verify_commit_graph_error;
1152
1153        progress = start_progress(_("Verifying commits in commit graph"),
1154                                  g->num_commits);
1155        for (i = 0; i < g->num_commits; i++) {
1156                struct commit *graph_commit, *odb_commit;
1157                struct commit_list *graph_parents, *odb_parents;
1158                uint32_t max_generation = 0;
1159
1160                display_progress(progress, i + 1);
1161                hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1162
1163                graph_commit = lookup_commit(r, &cur_oid);
1164                odb_commit = (struct commit *)create_object(r, cur_oid.hash, alloc_commit_node(r));
1165                if (parse_commit_internal(odb_commit, 0, 0)) {
1166                        graph_report("failed to parse %s from object database",
1167                                     oid_to_hex(&cur_oid));
1168                        continue;
1169                }
1170
1171                if (!oideq(&get_commit_tree_in_graph_one(r, g, graph_commit)->object.oid,
1172                           get_commit_tree_oid(odb_commit)))
1173                        graph_report("root tree OID for commit %s in commit-graph is %s != %s",
1174                                     oid_to_hex(&cur_oid),
1175                                     oid_to_hex(get_commit_tree_oid(graph_commit)),
1176                                     oid_to_hex(get_commit_tree_oid(odb_commit)));
1177
1178                graph_parents = graph_commit->parents;
1179                odb_parents = odb_commit->parents;
1180
1181                while (graph_parents) {
1182                        if (odb_parents == NULL) {
1183                                graph_report("commit-graph parent list for commit %s is too long",
1184                                             oid_to_hex(&cur_oid));
1185                                break;
1186                        }
1187
1188                        if (!oideq(&graph_parents->item->object.oid, &odb_parents->item->object.oid))
1189                                graph_report("commit-graph parent for %s is %s != %s",
1190                                             oid_to_hex(&cur_oid),
1191                                             oid_to_hex(&graph_parents->item->object.oid),
1192                                             oid_to_hex(&odb_parents->item->object.oid));
1193
1194                        if (graph_parents->item->generation > max_generation)
1195                                max_generation = graph_parents->item->generation;
1196
1197                        graph_parents = graph_parents->next;
1198                        odb_parents = odb_parents->next;
1199                }
1200
1201                if (odb_parents != NULL)
1202                        graph_report("commit-graph parent list for commit %s terminates early",
1203                                     oid_to_hex(&cur_oid));
1204
1205                if (!graph_commit->generation) {
1206                        if (generation_zero == GENERATION_NUMBER_EXISTS)
1207                                graph_report("commit-graph has generation number zero for commit %s, but non-zero elsewhere",
1208                                             oid_to_hex(&cur_oid));
1209                        generation_zero = GENERATION_ZERO_EXISTS;
1210                } else if (generation_zero == GENERATION_ZERO_EXISTS)
1211                        graph_report("commit-graph has non-zero generation number for commit %s, but zero elsewhere",
1212                                     oid_to_hex(&cur_oid));
1213
1214                if (generation_zero == GENERATION_ZERO_EXISTS)
1215                        continue;
1216
1217                /*
1218                 * If one of our parents has generation GENERATION_NUMBER_MAX, then
1219                 * our generation is also GENERATION_NUMBER_MAX. Decrement to avoid
1220                 * extra logic in the following condition.
1221                 */
1222                if (max_generation == GENERATION_NUMBER_MAX)
1223                        max_generation--;
1224
1225                if (graph_commit->generation != max_generation + 1)
1226                        graph_report("commit-graph generation for commit %s is %u != %u",
1227                                     oid_to_hex(&cur_oid),
1228                                     graph_commit->generation,
1229                                     max_generation + 1);
1230
1231                if (graph_commit->date != odb_commit->date)
1232                        graph_report("commit date for commit %s in commit-graph is %"PRItime" != %"PRItime,
1233                                     oid_to_hex(&cur_oid),
1234                                     graph_commit->date,
1235                                     odb_commit->date);
1236        }
1237        stop_progress(&progress);
1238
1239        return verify_commit_graph_error;
1240}
1241
1242void free_commit_graph(struct commit_graph *g)
1243{
1244        if (!g)
1245                return;
1246        if (g->graph_fd >= 0) {
1247                munmap((void *)g->data, g->data_len);
1248                g->data = NULL;
1249                close(g->graph_fd);
1250        }
1251        free(g);
1252}