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