commit.con commit contrib: add a script to initialize VS Code configuration (54c06c6)
   1#include "cache.h"
   2#include "tag.h"
   3#include "commit.h"
   4#include "commit-graph.h"
   5#include "repository.h"
   6#include "object-store.h"
   7#include "pkt-line.h"
   8#include "utf8.h"
   9#include "diff.h"
  10#include "revision.h"
  11#include "notes.h"
  12#include "alloc.h"
  13#include "gpg-interface.h"
  14#include "mergesort.h"
  15#include "commit-slab.h"
  16#include "prio-queue.h"
  17#include "sha1-lookup.h"
  18#include "wt-status.h"
  19#include "advice.h"
  20
  21static struct commit_extra_header *read_commit_extra_header_lines(const char *buf, size_t len, const char **);
  22
  23int save_commit_buffer = 1;
  24
  25const char *commit_type = "commit";
  26
  27struct commit *lookup_commit_reference_gently(const struct object_id *oid,
  28                                              int quiet)
  29{
  30        struct object *obj = deref_tag(parse_object(oid), NULL, 0);
  31
  32        if (!obj)
  33                return NULL;
  34        return object_as_type(obj, OBJ_COMMIT, quiet);
  35}
  36
  37struct commit *lookup_commit_reference(const struct object_id *oid)
  38{
  39        return lookup_commit_reference_gently(oid, 0);
  40}
  41
  42struct commit *lookup_commit_or_die(const struct object_id *oid, const char *ref_name)
  43{
  44        struct commit *c = lookup_commit_reference(oid);
  45        if (!c)
  46                die(_("could not parse %s"), ref_name);
  47        if (oidcmp(oid, &c->object.oid)) {
  48                warning(_("%s %s is not a commit!"),
  49                        ref_name, oid_to_hex(oid));
  50        }
  51        return c;
  52}
  53
  54struct commit *lookup_commit(const struct object_id *oid)
  55{
  56        struct object *obj = lookup_object(oid->hash);
  57        if (!obj)
  58                return create_object(the_repository, oid->hash,
  59                                     alloc_commit_node(the_repository));
  60        return object_as_type(obj, OBJ_COMMIT, 0);
  61}
  62
  63struct commit *lookup_commit_reference_by_name(const char *name)
  64{
  65        struct object_id oid;
  66        struct commit *commit;
  67
  68        if (get_oid_committish(name, &oid))
  69                return NULL;
  70        commit = lookup_commit_reference(&oid);
  71        if (parse_commit(commit))
  72                return NULL;
  73        return commit;
  74}
  75
  76static timestamp_t parse_commit_date(const char *buf, const char *tail)
  77{
  78        const char *dateptr;
  79
  80        if (buf + 6 >= tail)
  81                return 0;
  82        if (memcmp(buf, "author", 6))
  83                return 0;
  84        while (buf < tail && *buf++ != '\n')
  85                /* nada */;
  86        if (buf + 9 >= tail)
  87                return 0;
  88        if (memcmp(buf, "committer", 9))
  89                return 0;
  90        while (buf < tail && *buf++ != '>')
  91                /* nada */;
  92        if (buf >= tail)
  93                return 0;
  94        dateptr = buf;
  95        while (buf < tail && *buf++ != '\n')
  96                /* nada */;
  97        if (buf >= tail)
  98                return 0;
  99        /* dateptr < buf && buf[-1] == '\n', so parsing will stop at buf-1 */
 100        return parse_timestamp(dateptr, NULL, 10);
 101}
 102
 103static const unsigned char *commit_graft_sha1_access(size_t index, void *table)
 104{
 105        struct commit_graft **commit_graft_table = table;
 106        return commit_graft_table[index]->oid.hash;
 107}
 108
 109static int commit_graft_pos(struct repository *r, const unsigned char *sha1)
 110{
 111        return sha1_pos(sha1, r->parsed_objects->grafts,
 112                        r->parsed_objects->grafts_nr,
 113                        commit_graft_sha1_access);
 114}
 115
 116int register_commit_graft(struct repository *r, struct commit_graft *graft,
 117                          int ignore_dups)
 118{
 119        int pos = commit_graft_pos(r, graft->oid.hash);
 120
 121        if (0 <= pos) {
 122                if (ignore_dups)
 123                        free(graft);
 124                else {
 125                        free(r->parsed_objects->grafts[pos]);
 126                        r->parsed_objects->grafts[pos] = graft;
 127                }
 128                return 1;
 129        }
 130        pos = -pos - 1;
 131        ALLOC_GROW(r->parsed_objects->grafts,
 132                   r->parsed_objects->grafts_nr + 1,
 133                   r->parsed_objects->grafts_alloc);
 134        r->parsed_objects->grafts_nr++;
 135        if (pos < r->parsed_objects->grafts_nr)
 136                memmove(r->parsed_objects->grafts + pos + 1,
 137                        r->parsed_objects->grafts + pos,
 138                        (r->parsed_objects->grafts_nr - pos - 1) *
 139                        sizeof(*r->parsed_objects->grafts));
 140        r->parsed_objects->grafts[pos] = graft;
 141        return 0;
 142}
 143
 144struct commit_graft *read_graft_line(struct strbuf *line)
 145{
 146        /* The format is just "Commit Parent1 Parent2 ...\n" */
 147        int i, phase;
 148        const char *tail = NULL;
 149        struct commit_graft *graft = NULL;
 150        struct object_id dummy_oid, *oid;
 151
 152        strbuf_rtrim(line);
 153        if (!line->len || line->buf[0] == '#')
 154                return NULL;
 155        /*
 156         * phase 0 verifies line, counts hashes in line and allocates graft
 157         * phase 1 fills graft
 158         */
 159        for (phase = 0; phase < 2; phase++) {
 160                oid = graft ? &graft->oid : &dummy_oid;
 161                if (parse_oid_hex(line->buf, oid, &tail))
 162                        goto bad_graft_data;
 163                for (i = 0; *tail != '\0'; i++) {
 164                        oid = graft ? &graft->parent[i] : &dummy_oid;
 165                        if (!isspace(*tail++) || parse_oid_hex(tail, oid, &tail))
 166                                goto bad_graft_data;
 167                }
 168                if (!graft) {
 169                        graft = xmalloc(st_add(sizeof(*graft),
 170                                               st_mult(sizeof(struct object_id), i)));
 171                        graft->nr_parent = i;
 172                }
 173        }
 174        return graft;
 175
 176bad_graft_data:
 177        error("bad graft data: %s", line->buf);
 178        assert(!graft);
 179        return NULL;
 180}
 181
 182static int read_graft_file(struct repository *r, const char *graft_file)
 183{
 184        FILE *fp = fopen_or_warn(graft_file, "r");
 185        struct strbuf buf = STRBUF_INIT;
 186        if (!fp)
 187                return -1;
 188        if (advice_graft_file_deprecated)
 189                advise(_("Support for <GIT_DIR>/info/grafts is deprecated\n"
 190                         "and will be removed in a future Git version.\n"
 191                         "\n"
 192                         "Please use \"git replace --convert-graft-file\"\n"
 193                         "to convert the grafts into replace refs.\n"
 194                         "\n"
 195                         "Turn this message off by running\n"
 196                         "\"git config advice.graftFileDeprecated false\""));
 197        while (!strbuf_getwholeline(&buf, fp, '\n')) {
 198                /* The format is just "Commit Parent1 Parent2 ...\n" */
 199                struct commit_graft *graft = read_graft_line(&buf);
 200                if (!graft)
 201                        continue;
 202                if (register_commit_graft(r, graft, 1))
 203                        error("duplicate graft data: %s", buf.buf);
 204        }
 205        fclose(fp);
 206        strbuf_release(&buf);
 207        return 0;
 208}
 209
 210static void prepare_commit_graft(struct repository *r)
 211{
 212        char *graft_file;
 213
 214        if (r->parsed_objects->commit_graft_prepared)
 215                return;
 216        if (!startup_info->have_repository)
 217                return;
 218
 219        graft_file = get_graft_file(r);
 220        read_graft_file(r, graft_file);
 221        /* make sure shallows are read */
 222        is_repository_shallow(r);
 223        r->parsed_objects->commit_graft_prepared = 1;
 224}
 225
 226struct commit_graft *lookup_commit_graft(struct repository *r, const struct object_id *oid)
 227{
 228        int pos;
 229        prepare_commit_graft(r);
 230        pos = commit_graft_pos(r, oid->hash);
 231        if (pos < 0)
 232                return NULL;
 233        return r->parsed_objects->grafts[pos];
 234}
 235
 236int for_each_commit_graft(each_commit_graft_fn fn, void *cb_data)
 237{
 238        int i, ret;
 239        for (i = ret = 0; i < the_repository->parsed_objects->grafts_nr && !ret; i++)
 240                ret = fn(the_repository->parsed_objects->grafts[i], cb_data);
 241        return ret;
 242}
 243
 244int unregister_shallow(const struct object_id *oid)
 245{
 246        int pos = commit_graft_pos(the_repository, oid->hash);
 247        if (pos < 0)
 248                return -1;
 249        if (pos + 1 < the_repository->parsed_objects->grafts_nr)
 250                MOVE_ARRAY(the_repository->parsed_objects->grafts + pos,
 251                           the_repository->parsed_objects->grafts + pos + 1,
 252                           the_repository->parsed_objects->grafts_nr - pos - 1);
 253        the_repository->parsed_objects->grafts_nr--;
 254        return 0;
 255}
 256
 257struct commit_buffer {
 258        void *buffer;
 259        unsigned long size;
 260};
 261define_commit_slab(buffer_slab, struct commit_buffer);
 262static struct buffer_slab buffer_slab = COMMIT_SLAB_INIT(1, buffer_slab);
 263
 264void set_commit_buffer(struct commit *commit, void *buffer, unsigned long size)
 265{
 266        struct commit_buffer *v = buffer_slab_at(&buffer_slab, commit);
 267        v->buffer = buffer;
 268        v->size = size;
 269}
 270
 271const void *get_cached_commit_buffer(const struct commit *commit, unsigned long *sizep)
 272{
 273        struct commit_buffer *v = buffer_slab_peek(&buffer_slab, commit);
 274        if (!v) {
 275                if (sizep)
 276                        *sizep = 0;
 277                return NULL;
 278        }
 279        if (sizep)
 280                *sizep = v->size;
 281        return v->buffer;
 282}
 283
 284const void *get_commit_buffer(const struct commit *commit, unsigned long *sizep)
 285{
 286        const void *ret = get_cached_commit_buffer(commit, sizep);
 287        if (!ret) {
 288                enum object_type type;
 289                unsigned long size;
 290                ret = read_object_file(&commit->object.oid, &type, &size);
 291                if (!ret)
 292                        die("cannot read commit object %s",
 293                            oid_to_hex(&commit->object.oid));
 294                if (type != OBJ_COMMIT)
 295                        die("expected commit for %s, got %s",
 296                            oid_to_hex(&commit->object.oid), type_name(type));
 297                if (sizep)
 298                        *sizep = size;
 299        }
 300        return ret;
 301}
 302
 303void unuse_commit_buffer(const struct commit *commit, const void *buffer)
 304{
 305        struct commit_buffer *v = buffer_slab_peek(&buffer_slab, commit);
 306        if (!(v && v->buffer == buffer))
 307                free((void *)buffer);
 308}
 309
 310void free_commit_buffer(struct commit *commit)
 311{
 312        struct commit_buffer *v = buffer_slab_peek(&buffer_slab, commit);
 313        if (v) {
 314                FREE_AND_NULL(v->buffer);
 315                v->size = 0;
 316        }
 317}
 318
 319struct tree *get_commit_tree(const struct commit *commit)
 320{
 321        if (commit->maybe_tree || !commit->object.parsed)
 322                return commit->maybe_tree;
 323
 324        if (commit->graph_pos == COMMIT_NOT_FROM_GRAPH)
 325                BUG("commit has NULL tree, but was not loaded from commit-graph");
 326
 327        return get_commit_tree_in_graph(commit);
 328}
 329
 330struct object_id *get_commit_tree_oid(const struct commit *commit)
 331{
 332        return &get_commit_tree(commit)->object.oid;
 333}
 334
 335void release_commit_memory(struct commit *c)
 336{
 337        c->maybe_tree = NULL;
 338        c->index = 0;
 339        free_commit_buffer(c);
 340        free_commit_list(c->parents);
 341        /* TODO: what about commit->util? */
 342
 343        c->object.parsed = 0;
 344}
 345
 346const void *detach_commit_buffer(struct commit *commit, unsigned long *sizep)
 347{
 348        struct commit_buffer *v = buffer_slab_peek(&buffer_slab, commit);
 349        void *ret;
 350
 351        if (!v) {
 352                if (sizep)
 353                        *sizep = 0;
 354                return NULL;
 355        }
 356        ret = v->buffer;
 357        if (sizep)
 358                *sizep = v->size;
 359
 360        v->buffer = NULL;
 361        v->size = 0;
 362        return ret;
 363}
 364
 365int parse_commit_buffer(struct commit *item, const void *buffer, unsigned long size, int check_graph)
 366{
 367        const char *tail = buffer;
 368        const char *bufptr = buffer;
 369        struct object_id parent;
 370        struct commit_list **pptr;
 371        struct commit_graft *graft;
 372        const int tree_entry_len = GIT_SHA1_HEXSZ + 5;
 373        const int parent_entry_len = GIT_SHA1_HEXSZ + 7;
 374
 375        if (item->object.parsed)
 376                return 0;
 377        item->object.parsed = 1;
 378        tail += size;
 379        if (tail <= bufptr + tree_entry_len + 1 || memcmp(bufptr, "tree ", 5) ||
 380                        bufptr[tree_entry_len] != '\n')
 381                return error("bogus commit object %s", oid_to_hex(&item->object.oid));
 382        if (get_oid_hex(bufptr + 5, &parent) < 0)
 383                return error("bad tree pointer in commit %s",
 384                             oid_to_hex(&item->object.oid));
 385        item->maybe_tree = lookup_tree(&parent);
 386        bufptr += tree_entry_len + 1; /* "tree " + "hex sha1" + "\n" */
 387        pptr = &item->parents;
 388
 389        graft = lookup_commit_graft(the_repository, &item->object.oid);
 390        while (bufptr + parent_entry_len < tail && !memcmp(bufptr, "parent ", 7)) {
 391                struct commit *new_parent;
 392
 393                if (tail <= bufptr + parent_entry_len + 1 ||
 394                    get_oid_hex(bufptr + 7, &parent) ||
 395                    bufptr[parent_entry_len] != '\n')
 396                        return error("bad parents in commit %s", oid_to_hex(&item->object.oid));
 397                bufptr += parent_entry_len + 1;
 398                /*
 399                 * The clone is shallow if nr_parent < 0, and we must
 400                 * not traverse its real parents even when we unhide them.
 401                 */
 402                if (graft && (graft->nr_parent < 0 || grafts_replace_parents))
 403                        continue;
 404                new_parent = lookup_commit(&parent);
 405                if (new_parent)
 406                        pptr = &commit_list_insert(new_parent, pptr)->next;
 407        }
 408        if (graft) {
 409                int i;
 410                struct commit *new_parent;
 411                for (i = 0; i < graft->nr_parent; i++) {
 412                        new_parent = lookup_commit(&graft->parent[i]);
 413                        if (!new_parent)
 414                                continue;
 415                        pptr = &commit_list_insert(new_parent, pptr)->next;
 416                }
 417        }
 418        item->date = parse_commit_date(bufptr, tail);
 419
 420        if (check_graph)
 421                load_commit_graph_info(item);
 422
 423        return 0;
 424}
 425
 426int parse_commit_gently(struct commit *item, int quiet_on_missing)
 427{
 428        enum object_type type;
 429        void *buffer;
 430        unsigned long size;
 431        int ret;
 432
 433        if (!item)
 434                return -1;
 435        if (item->object.parsed)
 436                return 0;
 437        if (parse_commit_in_graph(item))
 438                return 0;
 439        buffer = read_object_file(&item->object.oid, &type, &size);
 440        if (!buffer)
 441                return quiet_on_missing ? -1 :
 442                        error("Could not read %s",
 443                             oid_to_hex(&item->object.oid));
 444        if (type != OBJ_COMMIT) {
 445                free(buffer);
 446                return error("Object %s not a commit",
 447                             oid_to_hex(&item->object.oid));
 448        }
 449        ret = parse_commit_buffer(item, buffer, size, 0);
 450        if (save_commit_buffer && !ret) {
 451                set_commit_buffer(item, buffer, size);
 452                return 0;
 453        }
 454        free(buffer);
 455        return ret;
 456}
 457
 458void parse_commit_or_die(struct commit *item)
 459{
 460        if (parse_commit(item))
 461                die("unable to parse commit %s",
 462                    item ? oid_to_hex(&item->object.oid) : "(null)");
 463}
 464
 465int find_commit_subject(const char *commit_buffer, const char **subject)
 466{
 467        const char *eol;
 468        const char *p = commit_buffer;
 469
 470        while (*p && (*p != '\n' || p[1] != '\n'))
 471                p++;
 472        if (*p) {
 473                p = skip_blank_lines(p + 2);
 474                eol = strchrnul(p, '\n');
 475        } else
 476                eol = p;
 477
 478        *subject = p;
 479
 480        return eol - p;
 481}
 482
 483struct commit_list *commit_list_insert(struct commit *item, struct commit_list **list_p)
 484{
 485        struct commit_list *new_list = xmalloc(sizeof(struct commit_list));
 486        new_list->item = item;
 487        new_list->next = *list_p;
 488        *list_p = new_list;
 489        return new_list;
 490}
 491
 492unsigned commit_list_count(const struct commit_list *l)
 493{
 494        unsigned c = 0;
 495        for (; l; l = l->next )
 496                c++;
 497        return c;
 498}
 499
 500struct commit_list *copy_commit_list(struct commit_list *list)
 501{
 502        struct commit_list *head = NULL;
 503        struct commit_list **pp = &head;
 504        while (list) {
 505                pp = commit_list_append(list->item, pp);
 506                list = list->next;
 507        }
 508        return head;
 509}
 510
 511void free_commit_list(struct commit_list *list)
 512{
 513        while (list)
 514                pop_commit(&list);
 515}
 516
 517struct commit_list * commit_list_insert_by_date(struct commit *item, struct commit_list **list)
 518{
 519        struct commit_list **pp = list;
 520        struct commit_list *p;
 521        while ((p = *pp) != NULL) {
 522                if (p->item->date < item->date) {
 523                        break;
 524                }
 525                pp = &p->next;
 526        }
 527        return commit_list_insert(item, pp);
 528}
 529
 530static int commit_list_compare_by_date(const void *a, const void *b)
 531{
 532        timestamp_t a_date = ((const struct commit_list *)a)->item->date;
 533        timestamp_t b_date = ((const struct commit_list *)b)->item->date;
 534        if (a_date < b_date)
 535                return 1;
 536        if (a_date > b_date)
 537                return -1;
 538        return 0;
 539}
 540
 541static void *commit_list_get_next(const void *a)
 542{
 543        return ((const struct commit_list *)a)->next;
 544}
 545
 546static void commit_list_set_next(void *a, void *next)
 547{
 548        ((struct commit_list *)a)->next = next;
 549}
 550
 551void commit_list_sort_by_date(struct commit_list **list)
 552{
 553        *list = llist_mergesort(*list, commit_list_get_next, commit_list_set_next,
 554                                commit_list_compare_by_date);
 555}
 556
 557struct commit *pop_most_recent_commit(struct commit_list **list,
 558                                      unsigned int mark)
 559{
 560        struct commit *ret = pop_commit(list);
 561        struct commit_list *parents = ret->parents;
 562
 563        while (parents) {
 564                struct commit *commit = parents->item;
 565                if (!parse_commit(commit) && !(commit->object.flags & mark)) {
 566                        commit->object.flags |= mark;
 567                        commit_list_insert_by_date(commit, list);
 568                }
 569                parents = parents->next;
 570        }
 571        return ret;
 572}
 573
 574static void clear_commit_marks_1(struct commit_list **plist,
 575                                 struct commit *commit, unsigned int mark)
 576{
 577        while (commit) {
 578                struct commit_list *parents;
 579
 580                if (!(mark & commit->object.flags))
 581                        return;
 582
 583                commit->object.flags &= ~mark;
 584
 585                parents = commit->parents;
 586                if (!parents)
 587                        return;
 588
 589                while ((parents = parents->next))
 590                        commit_list_insert(parents->item, plist);
 591
 592                commit = commit->parents->item;
 593        }
 594}
 595
 596void clear_commit_marks_many(int nr, struct commit **commit, unsigned int mark)
 597{
 598        struct commit_list *list = NULL;
 599
 600        while (nr--) {
 601                clear_commit_marks_1(&list, *commit, mark);
 602                commit++;
 603        }
 604        while (list)
 605                clear_commit_marks_1(&list, pop_commit(&list), mark);
 606}
 607
 608void clear_commit_marks(struct commit *commit, unsigned int mark)
 609{
 610        clear_commit_marks_many(1, &commit, mark);
 611}
 612
 613struct commit *pop_commit(struct commit_list **stack)
 614{
 615        struct commit_list *top = *stack;
 616        struct commit *item = top ? top->item : NULL;
 617
 618        if (top) {
 619                *stack = top->next;
 620                free(top);
 621        }
 622        return item;
 623}
 624
 625/*
 626 * Topological sort support
 627 */
 628
 629/* count number of children that have not been emitted */
 630define_commit_slab(indegree_slab, int);
 631
 632/* record author-date for each commit object */
 633define_commit_slab(author_date_slab, unsigned long);
 634
 635static void record_author_date(struct author_date_slab *author_date,
 636                               struct commit *commit)
 637{
 638        const char *buffer = get_commit_buffer(commit, NULL);
 639        struct ident_split ident;
 640        const char *ident_line;
 641        size_t ident_len;
 642        char *date_end;
 643        timestamp_t date;
 644
 645        ident_line = find_commit_header(buffer, "author", &ident_len);
 646        if (!ident_line)
 647                goto fail_exit; /* no author line */
 648        if (split_ident_line(&ident, ident_line, ident_len) ||
 649            !ident.date_begin || !ident.date_end)
 650                goto fail_exit; /* malformed "author" line */
 651
 652        date = parse_timestamp(ident.date_begin, &date_end, 10);
 653        if (date_end != ident.date_end)
 654                goto fail_exit; /* malformed date */
 655        *(author_date_slab_at(author_date, commit)) = date;
 656
 657fail_exit:
 658        unuse_commit_buffer(commit, buffer);
 659}
 660
 661static int compare_commits_by_author_date(const void *a_, const void *b_,
 662                                          void *cb_data)
 663{
 664        const struct commit *a = a_, *b = b_;
 665        struct author_date_slab *author_date = cb_data;
 666        timestamp_t a_date = *(author_date_slab_at(author_date, a));
 667        timestamp_t b_date = *(author_date_slab_at(author_date, b));
 668
 669        /* newer commits with larger date first */
 670        if (a_date < b_date)
 671                return 1;
 672        else if (a_date > b_date)
 673                return -1;
 674        return 0;
 675}
 676
 677int compare_commits_by_gen_then_commit_date(const void *a_, const void *b_, void *unused)
 678{
 679        const struct commit *a = a_, *b = b_;
 680
 681        /* newer commits first */
 682        if (a->generation < b->generation)
 683                return 1;
 684        else if (a->generation > b->generation)
 685                return -1;
 686
 687        /* use date as a heuristic when generations are equal */
 688        if (a->date < b->date)
 689                return 1;
 690        else if (a->date > b->date)
 691                return -1;
 692        return 0;
 693}
 694
 695int compare_commits_by_commit_date(const void *a_, const void *b_, void *unused)
 696{
 697        const struct commit *a = a_, *b = b_;
 698        /* newer commits with larger date first */
 699        if (a->date < b->date)
 700                return 1;
 701        else if (a->date > b->date)
 702                return -1;
 703        return 0;
 704}
 705
 706/*
 707 * Performs an in-place topological sort on the list supplied.
 708 */
 709void sort_in_topological_order(struct commit_list **list, enum rev_sort_order sort_order)
 710{
 711        struct commit_list *next, *orig = *list;
 712        struct commit_list **pptr;
 713        struct indegree_slab indegree;
 714        struct prio_queue queue;
 715        struct commit *commit;
 716        struct author_date_slab author_date;
 717
 718        if (!orig)
 719                return;
 720        *list = NULL;
 721
 722        init_indegree_slab(&indegree);
 723        memset(&queue, '\0', sizeof(queue));
 724
 725        switch (sort_order) {
 726        default: /* REV_SORT_IN_GRAPH_ORDER */
 727                queue.compare = NULL;
 728                break;
 729        case REV_SORT_BY_COMMIT_DATE:
 730                queue.compare = compare_commits_by_commit_date;
 731                break;
 732        case REV_SORT_BY_AUTHOR_DATE:
 733                init_author_date_slab(&author_date);
 734                queue.compare = compare_commits_by_author_date;
 735                queue.cb_data = &author_date;
 736                break;
 737        }
 738
 739        /* Mark them and clear the indegree */
 740        for (next = orig; next; next = next->next) {
 741                struct commit *commit = next->item;
 742                *(indegree_slab_at(&indegree, commit)) = 1;
 743                /* also record the author dates, if needed */
 744                if (sort_order == REV_SORT_BY_AUTHOR_DATE)
 745                        record_author_date(&author_date, commit);
 746        }
 747
 748        /* update the indegree */
 749        for (next = orig; next; next = next->next) {
 750                struct commit_list *parents = next->item->parents;
 751                while (parents) {
 752                        struct commit *parent = parents->item;
 753                        int *pi = indegree_slab_at(&indegree, parent);
 754
 755                        if (*pi)
 756                                (*pi)++;
 757                        parents = parents->next;
 758                }
 759        }
 760
 761        /*
 762         * find the tips
 763         *
 764         * tips are nodes not reachable from any other node in the list
 765         *
 766         * the tips serve as a starting set for the work queue.
 767         */
 768        for (next = orig; next; next = next->next) {
 769                struct commit *commit = next->item;
 770
 771                if (*(indegree_slab_at(&indegree, commit)) == 1)
 772                        prio_queue_put(&queue, commit);
 773        }
 774
 775        /*
 776         * This is unfortunate; the initial tips need to be shown
 777         * in the order given from the revision traversal machinery.
 778         */
 779        if (sort_order == REV_SORT_IN_GRAPH_ORDER)
 780                prio_queue_reverse(&queue);
 781
 782        /* We no longer need the commit list */
 783        free_commit_list(orig);
 784
 785        pptr = list;
 786        *list = NULL;
 787        while ((commit = prio_queue_get(&queue)) != NULL) {
 788                struct commit_list *parents;
 789
 790                for (parents = commit->parents; parents ; parents = parents->next) {
 791                        struct commit *parent = parents->item;
 792                        int *pi = indegree_slab_at(&indegree, parent);
 793
 794                        if (!*pi)
 795                                continue;
 796
 797                        /*
 798                         * parents are only enqueued for emission
 799                         * when all their children have been emitted thereby
 800                         * guaranteeing topological order.
 801                         */
 802                        if (--(*pi) == 1)
 803                                prio_queue_put(&queue, parent);
 804                }
 805                /*
 806                 * all children of commit have already been
 807                 * emitted. we can emit it now.
 808                 */
 809                *(indegree_slab_at(&indegree, commit)) = 0;
 810
 811                pptr = &commit_list_insert(commit, pptr)->next;
 812        }
 813
 814        clear_indegree_slab(&indegree);
 815        clear_prio_queue(&queue);
 816        if (sort_order == REV_SORT_BY_AUTHOR_DATE)
 817                clear_author_date_slab(&author_date);
 818}
 819
 820/* merge-base stuff */
 821
 822/* Remember to update object flag allocation in object.h */
 823#define PARENT1         (1u<<16)
 824#define PARENT2         (1u<<17)
 825#define STALE           (1u<<18)
 826#define RESULT          (1u<<19)
 827
 828static const unsigned all_flags = (PARENT1 | PARENT2 | STALE | RESULT);
 829
 830static int queue_has_nonstale(struct prio_queue *queue)
 831{
 832        int i;
 833        for (i = 0; i < queue->nr; i++) {
 834                struct commit *commit = queue->array[i].data;
 835                if (!(commit->object.flags & STALE))
 836                        return 1;
 837        }
 838        return 0;
 839}
 840
 841/* all input commits in one and twos[] must have been parsed! */
 842static struct commit_list *paint_down_to_common(struct commit *one, int n,
 843                                                struct commit **twos,
 844                                                int min_generation)
 845{
 846        struct prio_queue queue = { compare_commits_by_gen_then_commit_date };
 847        struct commit_list *result = NULL;
 848        int i;
 849        uint32_t last_gen = GENERATION_NUMBER_INFINITY;
 850
 851        one->object.flags |= PARENT1;
 852        if (!n) {
 853                commit_list_append(one, &result);
 854                return result;
 855        }
 856        prio_queue_put(&queue, one);
 857
 858        for (i = 0; i < n; i++) {
 859                twos[i]->object.flags |= PARENT2;
 860                prio_queue_put(&queue, twos[i]);
 861        }
 862
 863        while (queue_has_nonstale(&queue)) {
 864                struct commit *commit = prio_queue_get(&queue);
 865                struct commit_list *parents;
 866                int flags;
 867
 868                if (commit->generation > last_gen)
 869                        BUG("bad generation skip %8x > %8x at %s",
 870                            commit->generation, last_gen,
 871                            oid_to_hex(&commit->object.oid));
 872                last_gen = commit->generation;
 873
 874                if (commit->generation < min_generation)
 875                        break;
 876
 877                flags = commit->object.flags & (PARENT1 | PARENT2 | STALE);
 878                if (flags == (PARENT1 | PARENT2)) {
 879                        if (!(commit->object.flags & RESULT)) {
 880                                commit->object.flags |= RESULT;
 881                                commit_list_insert_by_date(commit, &result);
 882                        }
 883                        /* Mark parents of a found merge stale */
 884                        flags |= STALE;
 885                }
 886                parents = commit->parents;
 887                while (parents) {
 888                        struct commit *p = parents->item;
 889                        parents = parents->next;
 890                        if ((p->object.flags & flags) == flags)
 891                                continue;
 892                        if (parse_commit(p))
 893                                return NULL;
 894                        p->object.flags |= flags;
 895                        prio_queue_put(&queue, p);
 896                }
 897        }
 898
 899        clear_prio_queue(&queue);
 900        return result;
 901}
 902
 903static struct commit_list *merge_bases_many(struct commit *one, int n, struct commit **twos)
 904{
 905        struct commit_list *list = NULL;
 906        struct commit_list *result = NULL;
 907        int i;
 908
 909        for (i = 0; i < n; i++) {
 910                if (one == twos[i])
 911                        /*
 912                         * We do not mark this even with RESULT so we do not
 913                         * have to clean it up.
 914                         */
 915                        return commit_list_insert(one, &result);
 916        }
 917
 918        if (parse_commit(one))
 919                return NULL;
 920        for (i = 0; i < n; i++) {
 921                if (parse_commit(twos[i]))
 922                        return NULL;
 923        }
 924
 925        list = paint_down_to_common(one, n, twos, 0);
 926
 927        while (list) {
 928                struct commit *commit = pop_commit(&list);
 929                if (!(commit->object.flags & STALE))
 930                        commit_list_insert_by_date(commit, &result);
 931        }
 932        return result;
 933}
 934
 935struct commit_list *get_octopus_merge_bases(struct commit_list *in)
 936{
 937        struct commit_list *i, *j, *k, *ret = NULL;
 938
 939        if (!in)
 940                return ret;
 941
 942        commit_list_insert(in->item, &ret);
 943
 944        for (i = in->next; i; i = i->next) {
 945                struct commit_list *new_commits = NULL, *end = NULL;
 946
 947                for (j = ret; j; j = j->next) {
 948                        struct commit_list *bases;
 949                        bases = get_merge_bases(i->item, j->item);
 950                        if (!new_commits)
 951                                new_commits = bases;
 952                        else
 953                                end->next = bases;
 954                        for (k = bases; k; k = k->next)
 955                                end = k;
 956                }
 957                ret = new_commits;
 958        }
 959        return ret;
 960}
 961
 962static int remove_redundant(struct commit **array, int cnt)
 963{
 964        /*
 965         * Some commit in the array may be an ancestor of
 966         * another commit.  Move such commit to the end of
 967         * the array, and return the number of commits that
 968         * are independent from each other.
 969         */
 970        struct commit **work;
 971        unsigned char *redundant;
 972        int *filled_index;
 973        int i, j, filled;
 974
 975        work = xcalloc(cnt, sizeof(*work));
 976        redundant = xcalloc(cnt, 1);
 977        ALLOC_ARRAY(filled_index, cnt - 1);
 978
 979        for (i = 0; i < cnt; i++)
 980                parse_commit(array[i]);
 981        for (i = 0; i < cnt; i++) {
 982                struct commit_list *common;
 983                uint32_t min_generation = array[i]->generation;
 984
 985                if (redundant[i])
 986                        continue;
 987                for (j = filled = 0; j < cnt; j++) {
 988                        if (i == j || redundant[j])
 989                                continue;
 990                        filled_index[filled] = j;
 991                        work[filled++] = array[j];
 992
 993                        if (array[j]->generation < min_generation)
 994                                min_generation = array[j]->generation;
 995                }
 996                common = paint_down_to_common(array[i], filled, work,
 997                                              min_generation);
 998                if (array[i]->object.flags & PARENT2)
 999                        redundant[i] = 1;
1000                for (j = 0; j < filled; j++)
1001                        if (work[j]->object.flags & PARENT1)
1002                                redundant[filled_index[j]] = 1;
1003                clear_commit_marks(array[i], all_flags);
1004                clear_commit_marks_many(filled, work, all_flags);
1005                free_commit_list(common);
1006        }
1007
1008        /* Now collect the result */
1009        COPY_ARRAY(work, array, cnt);
1010        for (i = filled = 0; i < cnt; i++)
1011                if (!redundant[i])
1012                        array[filled++] = work[i];
1013        for (j = filled, i = 0; i < cnt; i++)
1014                if (redundant[i])
1015                        array[j++] = work[i];
1016        free(work);
1017        free(redundant);
1018        free(filled_index);
1019        return filled;
1020}
1021
1022static struct commit_list *get_merge_bases_many_0(struct commit *one,
1023                                                  int n,
1024                                                  struct commit **twos,
1025                                                  int cleanup)
1026{
1027        struct commit_list *list;
1028        struct commit **rslt;
1029        struct commit_list *result;
1030        int cnt, i;
1031
1032        result = merge_bases_many(one, n, twos);
1033        for (i = 0; i < n; i++) {
1034                if (one == twos[i])
1035                        return result;
1036        }
1037        if (!result || !result->next) {
1038                if (cleanup) {
1039                        clear_commit_marks(one, all_flags);
1040                        clear_commit_marks_many(n, twos, all_flags);
1041                }
1042                return result;
1043        }
1044
1045        /* There are more than one */
1046        cnt = commit_list_count(result);
1047        rslt = xcalloc(cnt, sizeof(*rslt));
1048        for (list = result, i = 0; list; list = list->next)
1049                rslt[i++] = list->item;
1050        free_commit_list(result);
1051
1052        clear_commit_marks(one, all_flags);
1053        clear_commit_marks_many(n, twos, all_flags);
1054
1055        cnt = remove_redundant(rslt, cnt);
1056        result = NULL;
1057        for (i = 0; i < cnt; i++)
1058                commit_list_insert_by_date(rslt[i], &result);
1059        free(rslt);
1060        return result;
1061}
1062
1063struct commit_list *get_merge_bases_many(struct commit *one,
1064                                         int n,
1065                                         struct commit **twos)
1066{
1067        return get_merge_bases_many_0(one, n, twos, 1);
1068}
1069
1070struct commit_list *get_merge_bases_many_dirty(struct commit *one,
1071                                               int n,
1072                                               struct commit **twos)
1073{
1074        return get_merge_bases_many_0(one, n, twos, 0);
1075}
1076
1077struct commit_list *get_merge_bases(struct commit *one, struct commit *two)
1078{
1079        return get_merge_bases_many_0(one, 1, &two, 1);
1080}
1081
1082/*
1083 * Is "commit" a descendant of one of the elements on the "with_commit" list?
1084 */
1085int is_descendant_of(struct commit *commit, struct commit_list *with_commit)
1086{
1087        if (!with_commit)
1088                return 1;
1089        while (with_commit) {
1090                struct commit *other;
1091
1092                other = with_commit->item;
1093                with_commit = with_commit->next;
1094                if (in_merge_bases(other, commit))
1095                        return 1;
1096        }
1097        return 0;
1098}
1099
1100/*
1101 * Is "commit" an ancestor of one of the "references"?
1102 */
1103int in_merge_bases_many(struct commit *commit, int nr_reference, struct commit **reference)
1104{
1105        struct commit_list *bases;
1106        int ret = 0, i;
1107        uint32_t min_generation = GENERATION_NUMBER_INFINITY;
1108
1109        if (parse_commit(commit))
1110                return ret;
1111        for (i = 0; i < nr_reference; i++) {
1112                if (parse_commit(reference[i]))
1113                        return ret;
1114                if (reference[i]->generation < min_generation)
1115                        min_generation = reference[i]->generation;
1116        }
1117
1118        if (commit->generation > min_generation)
1119                return ret;
1120
1121        bases = paint_down_to_common(commit, nr_reference, reference, commit->generation);
1122        if (commit->object.flags & PARENT2)
1123                ret = 1;
1124        clear_commit_marks(commit, all_flags);
1125        clear_commit_marks_many(nr_reference, reference, all_flags);
1126        free_commit_list(bases);
1127        return ret;
1128}
1129
1130/*
1131 * Is "commit" an ancestor of (i.e. reachable from) the "reference"?
1132 */
1133int in_merge_bases(struct commit *commit, struct commit *reference)
1134{
1135        return in_merge_bases_many(commit, 1, &reference);
1136}
1137
1138struct commit_list *reduce_heads(struct commit_list *heads)
1139{
1140        struct commit_list *p;
1141        struct commit_list *result = NULL, **tail = &result;
1142        struct commit **array;
1143        int num_head, i;
1144
1145        if (!heads)
1146                return NULL;
1147
1148        /* Uniquify */
1149        for (p = heads; p; p = p->next)
1150                p->item->object.flags &= ~STALE;
1151        for (p = heads, num_head = 0; p; p = p->next) {
1152                if (p->item->object.flags & STALE)
1153                        continue;
1154                p->item->object.flags |= STALE;
1155                num_head++;
1156        }
1157        array = xcalloc(num_head, sizeof(*array));
1158        for (p = heads, i = 0; p; p = p->next) {
1159                if (p->item->object.flags & STALE) {
1160                        array[i++] = p->item;
1161                        p->item->object.flags &= ~STALE;
1162                }
1163        }
1164        num_head = remove_redundant(array, num_head);
1165        for (i = 0; i < num_head; i++)
1166                tail = &commit_list_insert(array[i], tail)->next;
1167        free(array);
1168        return result;
1169}
1170
1171void reduce_heads_replace(struct commit_list **heads)
1172{
1173        struct commit_list *result = reduce_heads(*heads);
1174        free_commit_list(*heads);
1175        *heads = result;
1176}
1177
1178static const char gpg_sig_header[] = "gpgsig";
1179static const int gpg_sig_header_len = sizeof(gpg_sig_header) - 1;
1180
1181static int do_sign_commit(struct strbuf *buf, const char *keyid)
1182{
1183        struct strbuf sig = STRBUF_INIT;
1184        int inspos, copypos;
1185        const char *eoh;
1186
1187        /* find the end of the header */
1188        eoh = strstr(buf->buf, "\n\n");
1189        if (!eoh)
1190                inspos = buf->len;
1191        else
1192                inspos = eoh - buf->buf + 1;
1193
1194        if (!keyid || !*keyid)
1195                keyid = get_signing_key();
1196        if (sign_buffer(buf, &sig, keyid)) {
1197                strbuf_release(&sig);
1198                return -1;
1199        }
1200
1201        for (copypos = 0; sig.buf[copypos]; ) {
1202                const char *bol = sig.buf + copypos;
1203                const char *eol = strchrnul(bol, '\n');
1204                int len = (eol - bol) + !!*eol;
1205
1206                if (!copypos) {
1207                        strbuf_insert(buf, inspos, gpg_sig_header, gpg_sig_header_len);
1208                        inspos += gpg_sig_header_len;
1209                }
1210                strbuf_insert(buf, inspos++, " ", 1);
1211                strbuf_insert(buf, inspos, bol, len);
1212                inspos += len;
1213                copypos += len;
1214        }
1215        strbuf_release(&sig);
1216        return 0;
1217}
1218
1219int parse_signed_commit(const struct commit *commit,
1220                        struct strbuf *payload, struct strbuf *signature)
1221{
1222
1223        unsigned long size;
1224        const char *buffer = get_commit_buffer(commit, &size);
1225        int in_signature, saw_signature = -1;
1226        const char *line, *tail;
1227
1228        line = buffer;
1229        tail = buffer + size;
1230        in_signature = 0;
1231        saw_signature = 0;
1232        while (line < tail) {
1233                const char *sig = NULL;
1234                const char *next = memchr(line, '\n', tail - line);
1235
1236                next = next ? next + 1 : tail;
1237                if (in_signature && line[0] == ' ')
1238                        sig = line + 1;
1239                else if (starts_with(line, gpg_sig_header) &&
1240                         line[gpg_sig_header_len] == ' ')
1241                        sig = line + gpg_sig_header_len + 1;
1242                if (sig) {
1243                        strbuf_add(signature, sig, next - sig);
1244                        saw_signature = 1;
1245                        in_signature = 1;
1246                } else {
1247                        if (*line == '\n')
1248                                /* dump the whole remainder of the buffer */
1249                                next = tail;
1250                        strbuf_add(payload, line, next - line);
1251                        in_signature = 0;
1252                }
1253                line = next;
1254        }
1255        unuse_commit_buffer(commit, buffer);
1256        return saw_signature;
1257}
1258
1259int remove_signature(struct strbuf *buf)
1260{
1261        const char *line = buf->buf;
1262        const char *tail = buf->buf + buf->len;
1263        int in_signature = 0;
1264        const char *sig_start = NULL;
1265        const char *sig_end = NULL;
1266
1267        while (line < tail) {
1268                const char *next = memchr(line, '\n', tail - line);
1269                next = next ? next + 1 : tail;
1270
1271                if (in_signature && line[0] == ' ')
1272                        sig_end = next;
1273                else if (starts_with(line, gpg_sig_header) &&
1274                         line[gpg_sig_header_len] == ' ') {
1275                        sig_start = line;
1276                        sig_end = next;
1277                        in_signature = 1;
1278                } else {
1279                        if (*line == '\n')
1280                                /* dump the whole remainder of the buffer */
1281                                next = tail;
1282                        in_signature = 0;
1283                }
1284                line = next;
1285        }
1286
1287        if (sig_start)
1288                strbuf_remove(buf, sig_start - buf->buf, sig_end - sig_start);
1289
1290        return sig_start != NULL;
1291}
1292
1293static void handle_signed_tag(struct commit *parent, struct commit_extra_header ***tail)
1294{
1295        struct merge_remote_desc *desc;
1296        struct commit_extra_header *mergetag;
1297        char *buf;
1298        unsigned long size, len;
1299        enum object_type type;
1300
1301        desc = merge_remote_util(parent);
1302        if (!desc || !desc->obj)
1303                return;
1304        buf = read_object_file(&desc->obj->oid, &type, &size);
1305        if (!buf || type != OBJ_TAG)
1306                goto free_return;
1307        len = parse_signature(buf, size);
1308        if (size == len)
1309                goto free_return;
1310        /*
1311         * We could verify this signature and either omit the tag when
1312         * it does not validate, but the integrator may not have the
1313         * public key of the signer of the tag he is merging, while a
1314         * later auditor may have it while auditing, so let's not run
1315         * verify-signed-buffer here for now...
1316         *
1317         * if (verify_signed_buffer(buf, len, buf + len, size - len, ...))
1318         *      warn("warning: signed tag unverified.");
1319         */
1320        mergetag = xcalloc(1, sizeof(*mergetag));
1321        mergetag->key = xstrdup("mergetag");
1322        mergetag->value = buf;
1323        mergetag->len = size;
1324
1325        **tail = mergetag;
1326        *tail = &mergetag->next;
1327        return;
1328
1329free_return:
1330        free(buf);
1331}
1332
1333int check_commit_signature(const struct commit *commit, struct signature_check *sigc)
1334{
1335        struct strbuf payload = STRBUF_INIT;
1336        struct strbuf signature = STRBUF_INIT;
1337        int ret = 1;
1338
1339        sigc->result = 'N';
1340
1341        if (parse_signed_commit(commit, &payload, &signature) <= 0)
1342                goto out;
1343        ret = check_signature(payload.buf, payload.len, signature.buf,
1344                signature.len, sigc);
1345
1346 out:
1347        strbuf_release(&payload);
1348        strbuf_release(&signature);
1349
1350        return ret;
1351}
1352
1353
1354
1355void append_merge_tag_headers(struct commit_list *parents,
1356                              struct commit_extra_header ***tail)
1357{
1358        while (parents) {
1359                struct commit *parent = parents->item;
1360                handle_signed_tag(parent, tail);
1361                parents = parents->next;
1362        }
1363}
1364
1365static void add_extra_header(struct strbuf *buffer,
1366                             struct commit_extra_header *extra)
1367{
1368        strbuf_addstr(buffer, extra->key);
1369        if (extra->len)
1370                strbuf_add_lines(buffer, " ", extra->value, extra->len);
1371        else
1372                strbuf_addch(buffer, '\n');
1373}
1374
1375struct commit_extra_header *read_commit_extra_headers(struct commit *commit,
1376                                                      const char **exclude)
1377{
1378        struct commit_extra_header *extra = NULL;
1379        unsigned long size;
1380        const char *buffer = get_commit_buffer(commit, &size);
1381        extra = read_commit_extra_header_lines(buffer, size, exclude);
1382        unuse_commit_buffer(commit, buffer);
1383        return extra;
1384}
1385
1386int for_each_mergetag(each_mergetag_fn fn, struct commit *commit, void *data)
1387{
1388        struct commit_extra_header *extra, *to_free;
1389        int res = 0;
1390
1391        to_free = read_commit_extra_headers(commit, NULL);
1392        for (extra = to_free; !res && extra; extra = extra->next) {
1393                if (strcmp(extra->key, "mergetag"))
1394                        continue; /* not a merge tag */
1395                res = fn(commit, extra, data);
1396        }
1397        free_commit_extra_headers(to_free);
1398        return res;
1399}
1400
1401static inline int standard_header_field(const char *field, size_t len)
1402{
1403        return ((len == 4 && !memcmp(field, "tree", 4)) ||
1404                (len == 6 && !memcmp(field, "parent", 6)) ||
1405                (len == 6 && !memcmp(field, "author", 6)) ||
1406                (len == 9 && !memcmp(field, "committer", 9)) ||
1407                (len == 8 && !memcmp(field, "encoding", 8)));
1408}
1409
1410static int excluded_header_field(const char *field, size_t len, const char **exclude)
1411{
1412        if (!exclude)
1413                return 0;
1414
1415        while (*exclude) {
1416                size_t xlen = strlen(*exclude);
1417                if (len == xlen && !memcmp(field, *exclude, xlen))
1418                        return 1;
1419                exclude++;
1420        }
1421        return 0;
1422}
1423
1424static struct commit_extra_header *read_commit_extra_header_lines(
1425        const char *buffer, size_t size,
1426        const char **exclude)
1427{
1428        struct commit_extra_header *extra = NULL, **tail = &extra, *it = NULL;
1429        const char *line, *next, *eof, *eob;
1430        struct strbuf buf = STRBUF_INIT;
1431
1432        for (line = buffer, eob = line + size;
1433             line < eob && *line != '\n';
1434             line = next) {
1435                next = memchr(line, '\n', eob - line);
1436                next = next ? next + 1 : eob;
1437                if (*line == ' ') {
1438                        /* continuation */
1439                        if (it)
1440                                strbuf_add(&buf, line + 1, next - (line + 1));
1441                        continue;
1442                }
1443                if (it)
1444                        it->value = strbuf_detach(&buf, &it->len);
1445                strbuf_reset(&buf);
1446                it = NULL;
1447
1448                eof = memchr(line, ' ', next - line);
1449                if (!eof)
1450                        eof = next;
1451                else if (standard_header_field(line, eof - line) ||
1452                         excluded_header_field(line, eof - line, exclude))
1453                        continue;
1454
1455                it = xcalloc(1, sizeof(*it));
1456                it->key = xmemdupz(line, eof-line);
1457                *tail = it;
1458                tail = &it->next;
1459                if (eof + 1 < next)
1460                        strbuf_add(&buf, eof + 1, next - (eof + 1));
1461        }
1462        if (it)
1463                it->value = strbuf_detach(&buf, &it->len);
1464        return extra;
1465}
1466
1467void free_commit_extra_headers(struct commit_extra_header *extra)
1468{
1469        while (extra) {
1470                struct commit_extra_header *next = extra->next;
1471                free(extra->key);
1472                free(extra->value);
1473                free(extra);
1474                extra = next;
1475        }
1476}
1477
1478int commit_tree(const char *msg, size_t msg_len, const struct object_id *tree,
1479                struct commit_list *parents, struct object_id *ret,
1480                const char *author, const char *sign_commit)
1481{
1482        struct commit_extra_header *extra = NULL, **tail = &extra;
1483        int result;
1484
1485        append_merge_tag_headers(parents, &tail);
1486        result = commit_tree_extended(msg, msg_len, tree, parents, ret,
1487                                      author, sign_commit, extra);
1488        free_commit_extra_headers(extra);
1489        return result;
1490}
1491
1492static int find_invalid_utf8(const char *buf, int len)
1493{
1494        int offset = 0;
1495        static const unsigned int max_codepoint[] = {
1496                0x7f, 0x7ff, 0xffff, 0x10ffff
1497        };
1498
1499        while (len) {
1500                unsigned char c = *buf++;
1501                int bytes, bad_offset;
1502                unsigned int codepoint;
1503                unsigned int min_val, max_val;
1504
1505                len--;
1506                offset++;
1507
1508                /* Simple US-ASCII? No worries. */
1509                if (c < 0x80)
1510                        continue;
1511
1512                bad_offset = offset-1;
1513
1514                /*
1515                 * Count how many more high bits set: that's how
1516                 * many more bytes this sequence should have.
1517                 */
1518                bytes = 0;
1519                while (c & 0x40) {
1520                        c <<= 1;
1521                        bytes++;
1522                }
1523
1524                /*
1525                 * Must be between 1 and 3 more bytes.  Longer sequences result in
1526                 * codepoints beyond U+10FFFF, which are guaranteed never to exist.
1527                 */
1528                if (bytes < 1 || 3 < bytes)
1529                        return bad_offset;
1530
1531                /* Do we *have* that many bytes? */
1532                if (len < bytes)
1533                        return bad_offset;
1534
1535                /*
1536                 * Place the encoded bits at the bottom of the value and compute the
1537                 * valid range.
1538                 */
1539                codepoint = (c & 0x7f) >> bytes;
1540                min_val = max_codepoint[bytes-1] + 1;
1541                max_val = max_codepoint[bytes];
1542
1543                offset += bytes;
1544                len -= bytes;
1545
1546                /* And verify that they are good continuation bytes */
1547                do {
1548                        codepoint <<= 6;
1549                        codepoint |= *buf & 0x3f;
1550                        if ((*buf++ & 0xc0) != 0x80)
1551                                return bad_offset;
1552                } while (--bytes);
1553
1554                /* Reject codepoints that are out of range for the sequence length. */
1555                if (codepoint < min_val || codepoint > max_val)
1556                        return bad_offset;
1557                /* Surrogates are only for UTF-16 and cannot be encoded in UTF-8. */
1558                if ((codepoint & 0x1ff800) == 0xd800)
1559                        return bad_offset;
1560                /* U+xxFFFE and U+xxFFFF are guaranteed non-characters. */
1561                if ((codepoint & 0xfffe) == 0xfffe)
1562                        return bad_offset;
1563                /* So are anything in the range U+FDD0..U+FDEF. */
1564                if (codepoint >= 0xfdd0 && codepoint <= 0xfdef)
1565                        return bad_offset;
1566        }
1567        return -1;
1568}
1569
1570/*
1571 * This verifies that the buffer is in proper utf8 format.
1572 *
1573 * If it isn't, it assumes any non-utf8 characters are Latin1,
1574 * and does the conversion.
1575 */
1576static int verify_utf8(struct strbuf *buf)
1577{
1578        int ok = 1;
1579        long pos = 0;
1580
1581        for (;;) {
1582                int bad;
1583                unsigned char c;
1584                unsigned char replace[2];
1585
1586                bad = find_invalid_utf8(buf->buf + pos, buf->len - pos);
1587                if (bad < 0)
1588                        return ok;
1589                pos += bad;
1590                ok = 0;
1591                c = buf->buf[pos];
1592                strbuf_remove(buf, pos, 1);
1593
1594                /* We know 'c' must be in the range 128-255 */
1595                replace[0] = 0xc0 + (c >> 6);
1596                replace[1] = 0x80 + (c & 0x3f);
1597                strbuf_insert(buf, pos, replace, 2);
1598                pos += 2;
1599        }
1600}
1601
1602static const char commit_utf8_warn[] =
1603N_("Warning: commit message did not conform to UTF-8.\n"
1604   "You may want to amend it after fixing the message, or set the config\n"
1605   "variable i18n.commitencoding to the encoding your project uses.\n");
1606
1607int commit_tree_extended(const char *msg, size_t msg_len,
1608                         const struct object_id *tree,
1609                         struct commit_list *parents, struct object_id *ret,
1610                         const char *author, const char *sign_commit,
1611                         struct commit_extra_header *extra)
1612{
1613        int result;
1614        int encoding_is_utf8;
1615        struct strbuf buffer;
1616
1617        assert_oid_type(tree, OBJ_TREE);
1618
1619        if (memchr(msg, '\0', msg_len))
1620                return error("a NUL byte in commit log message not allowed.");
1621
1622        /* Not having i18n.commitencoding is the same as having utf-8 */
1623        encoding_is_utf8 = is_encoding_utf8(git_commit_encoding);
1624
1625        strbuf_init(&buffer, 8192); /* should avoid reallocs for the headers */
1626        strbuf_addf(&buffer, "tree %s\n", oid_to_hex(tree));
1627
1628        /*
1629         * NOTE! This ordering means that the same exact tree merged with a
1630         * different order of parents will be a _different_ changeset even
1631         * if everything else stays the same.
1632         */
1633        while (parents) {
1634                struct commit *parent = pop_commit(&parents);
1635                strbuf_addf(&buffer, "parent %s\n",
1636                            oid_to_hex(&parent->object.oid));
1637        }
1638
1639        /* Person/date information */
1640        if (!author)
1641                author = git_author_info(IDENT_STRICT);
1642        strbuf_addf(&buffer, "author %s\n", author);
1643        strbuf_addf(&buffer, "committer %s\n", git_committer_info(IDENT_STRICT));
1644        if (!encoding_is_utf8)
1645                strbuf_addf(&buffer, "encoding %s\n", git_commit_encoding);
1646
1647        while (extra) {
1648                add_extra_header(&buffer, extra);
1649                extra = extra->next;
1650        }
1651        strbuf_addch(&buffer, '\n');
1652
1653        /* And add the comment */
1654        strbuf_add(&buffer, msg, msg_len);
1655
1656        /* And check the encoding */
1657        if (encoding_is_utf8 && !verify_utf8(&buffer))
1658                fprintf(stderr, _(commit_utf8_warn));
1659
1660        if (sign_commit && do_sign_commit(&buffer, sign_commit)) {
1661                result = -1;
1662                goto out;
1663        }
1664
1665        result = write_object_file(buffer.buf, buffer.len, commit_type, ret);
1666out:
1667        strbuf_release(&buffer);
1668        return result;
1669}
1670
1671define_commit_slab(merge_desc_slab, struct merge_remote_desc *);
1672static struct merge_desc_slab merge_desc_slab = COMMIT_SLAB_INIT(1, merge_desc_slab);
1673
1674struct merge_remote_desc *merge_remote_util(struct commit *commit)
1675{
1676        return *merge_desc_slab_at(&merge_desc_slab, commit);
1677}
1678
1679void set_merge_remote_desc(struct commit *commit,
1680                           const char *name, struct object *obj)
1681{
1682        struct merge_remote_desc *desc;
1683        FLEX_ALLOC_STR(desc, name, name);
1684        desc->obj = obj;
1685        *merge_desc_slab_at(&merge_desc_slab, commit) = desc;
1686}
1687
1688struct commit *get_merge_parent(const char *name)
1689{
1690        struct object *obj;
1691        struct commit *commit;
1692        struct object_id oid;
1693        if (get_oid(name, &oid))
1694                return NULL;
1695        obj = parse_object(&oid);
1696        commit = (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
1697        if (commit && !merge_remote_util(commit))
1698                set_merge_remote_desc(commit, name, obj);
1699        return commit;
1700}
1701
1702/*
1703 * Append a commit to the end of the commit_list.
1704 *
1705 * next starts by pointing to the variable that holds the head of an
1706 * empty commit_list, and is updated to point to the "next" field of
1707 * the last item on the list as new commits are appended.
1708 *
1709 * Usage example:
1710 *
1711 *     struct commit_list *list;
1712 *     struct commit_list **next = &list;
1713 *
1714 *     next = commit_list_append(c1, next);
1715 *     next = commit_list_append(c2, next);
1716 *     assert(commit_list_count(list) == 2);
1717 *     return list;
1718 */
1719struct commit_list **commit_list_append(struct commit *commit,
1720                                        struct commit_list **next)
1721{
1722        struct commit_list *new_commit = xmalloc(sizeof(struct commit_list));
1723        new_commit->item = commit;
1724        *next = new_commit;
1725        new_commit->next = NULL;
1726        return &new_commit->next;
1727}
1728
1729const char *find_commit_header(const char *msg, const char *key, size_t *out_len)
1730{
1731        int key_len = strlen(key);
1732        const char *line = msg;
1733
1734        while (line) {
1735                const char *eol = strchrnul(line, '\n');
1736
1737                if (line == eol)
1738                        return NULL;
1739
1740                if (eol - line > key_len &&
1741                    !strncmp(line, key, key_len) &&
1742                    line[key_len] == ' ') {
1743                        *out_len = eol - line - key_len - 1;
1744                        return line + key_len + 1;
1745                }
1746                line = *eol ? eol + 1 : NULL;
1747        }
1748        return NULL;
1749}
1750
1751/*
1752 * Inspect the given string and determine the true "end" of the log message, in
1753 * order to find where to put a new Signed-off-by: line.  Ignored are
1754 * trailing comment lines and blank lines.  To support "git commit -s
1755 * --amend" on an existing commit, we also ignore "Conflicts:".  To
1756 * support "git commit -v", we truncate at cut lines.
1757 *
1758 * Returns the number of bytes from the tail to ignore, to be fed as
1759 * the second parameter to append_signoff().
1760 */
1761int ignore_non_trailer(const char *buf, size_t len)
1762{
1763        int boc = 0;
1764        int bol = 0;
1765        int in_old_conflicts_block = 0;
1766        size_t cutoff = wt_status_locate_end(buf, len);
1767
1768        while (bol < cutoff) {
1769                const char *next_line = memchr(buf + bol, '\n', len - bol);
1770
1771                if (!next_line)
1772                        next_line = buf + len;
1773                else
1774                        next_line++;
1775
1776                if (buf[bol] == comment_line_char || buf[bol] == '\n') {
1777                        /* is this the first of the run of comments? */
1778                        if (!boc)
1779                                boc = bol;
1780                        /* otherwise, it is just continuing */
1781                } else if (starts_with(buf + bol, "Conflicts:\n")) {
1782                        in_old_conflicts_block = 1;
1783                        if (!boc)
1784                                boc = bol;
1785                } else if (in_old_conflicts_block && buf[bol] == '\t') {
1786                        ; /* a pathname in the conflicts block */
1787                } else if (boc) {
1788                        /* the previous was not trailing comment */
1789                        boc = 0;
1790                        in_old_conflicts_block = 0;
1791                }
1792                bol = next_line - buf;
1793        }
1794        return boc ? len - boc : len - cutoff;
1795}