b9ce569442cdaf6fc401901427bfac5727f9739a
   1#include "cache.h"
   2#include "tag.h"
   3#include "commit.h"
   4#include "pkt-line.h"
   5#include "utf8.h"
   6#include "diff.h"
   7#include "revision.h"
   8#include "notes.h"
   9#include "gpg-interface.h"
  10#include "mergesort.h"
  11
  12int save_commit_buffer = 1;
  13
  14const char *commit_type = "commit";
  15
  16static struct commit *check_commit(struct object *obj,
  17                                   const unsigned char *sha1,
  18                                   int quiet)
  19{
  20        if (obj->type != OBJ_COMMIT) {
  21                if (!quiet)
  22                        error("Object %s is a %s, not a commit",
  23                              sha1_to_hex(sha1), typename(obj->type));
  24                return NULL;
  25        }
  26        return (struct commit *) obj;
  27}
  28
  29struct commit *lookup_commit_reference_gently(const unsigned char *sha1,
  30                                              int quiet)
  31{
  32        struct object *obj = deref_tag(parse_object(sha1), NULL, 0);
  33
  34        if (!obj)
  35                return NULL;
  36        return check_commit(obj, sha1, quiet);
  37}
  38
  39struct commit *lookup_commit_reference(const unsigned char *sha1)
  40{
  41        return lookup_commit_reference_gently(sha1, 0);
  42}
  43
  44struct commit *lookup_commit_or_die(const unsigned char *sha1, const char *ref_name)
  45{
  46        struct commit *c = lookup_commit_reference(sha1);
  47        if (!c)
  48                die(_("could not parse %s"), ref_name);
  49        if (hashcmp(sha1, c->object.sha1)) {
  50                warning(_("%s %s is not a commit!"),
  51                        ref_name, sha1_to_hex(sha1));
  52        }
  53        return c;
  54}
  55
  56struct commit *lookup_commit(const unsigned char *sha1)
  57{
  58        struct object *obj = lookup_object(sha1);
  59        if (!obj)
  60                return create_object(sha1, OBJ_COMMIT, alloc_commit_node());
  61        if (!obj->type)
  62                obj->type = OBJ_COMMIT;
  63        return check_commit(obj, sha1, 0);
  64}
  65
  66struct commit *lookup_commit_reference_by_name(const char *name)
  67{
  68        unsigned char sha1[20];
  69        struct commit *commit;
  70
  71        if (get_sha1(name, sha1))
  72                return NULL;
  73        commit = lookup_commit_reference(sha1);
  74        if (!commit || parse_commit(commit))
  75                return NULL;
  76        return commit;
  77}
  78
  79static unsigned long parse_commit_date(const char *buf, const char *tail)
  80{
  81        const char *dateptr;
  82
  83        if (buf + 6 >= tail)
  84                return 0;
  85        if (memcmp(buf, "author", 6))
  86                return 0;
  87        while (buf < tail && *buf++ != '\n')
  88                /* nada */;
  89        if (buf + 9 >= tail)
  90                return 0;
  91        if (memcmp(buf, "committer", 9))
  92                return 0;
  93        while (buf < tail && *buf++ != '>')
  94                /* nada */;
  95        if (buf >= tail)
  96                return 0;
  97        dateptr = buf;
  98        while (buf < tail && *buf++ != '\n')
  99                /* nada */;
 100        if (buf >= tail)
 101                return 0;
 102        /* dateptr < buf && buf[-1] == '\n', so strtoul will stop at buf-1 */
 103        return strtoul(dateptr, NULL, 10);
 104}
 105
 106static struct commit_graft **commit_graft;
 107static int commit_graft_alloc, commit_graft_nr;
 108
 109static int commit_graft_pos(const unsigned char *sha1)
 110{
 111        int lo, hi;
 112        lo = 0;
 113        hi = commit_graft_nr;
 114        while (lo < hi) {
 115                int mi = (lo + hi) / 2;
 116                struct commit_graft *graft = commit_graft[mi];
 117                int cmp = hashcmp(sha1, graft->sha1);
 118                if (!cmp)
 119                        return mi;
 120                if (cmp < 0)
 121                        hi = mi;
 122                else
 123                        lo = mi + 1;
 124        }
 125        return -lo - 1;
 126}
 127
 128int register_commit_graft(struct commit_graft *graft, int ignore_dups)
 129{
 130        int pos = commit_graft_pos(graft->sha1);
 131
 132        if (0 <= pos) {
 133                if (ignore_dups)
 134                        free(graft);
 135                else {
 136                        free(commit_graft[pos]);
 137                        commit_graft[pos] = graft;
 138                }
 139                return 1;
 140        }
 141        pos = -pos - 1;
 142        if (commit_graft_alloc <= ++commit_graft_nr) {
 143                commit_graft_alloc = alloc_nr(commit_graft_alloc);
 144                commit_graft = xrealloc(commit_graft,
 145                                        sizeof(*commit_graft) *
 146                                        commit_graft_alloc);
 147        }
 148        if (pos < commit_graft_nr)
 149                memmove(commit_graft + pos + 1,
 150                        commit_graft + pos,
 151                        (commit_graft_nr - pos - 1) *
 152                        sizeof(*commit_graft));
 153        commit_graft[pos] = graft;
 154        return 0;
 155}
 156
 157struct commit_graft *read_graft_line(char *buf, int len)
 158{
 159        /* The format is just "Commit Parent1 Parent2 ...\n" */
 160        int i;
 161        struct commit_graft *graft = NULL;
 162
 163        while (len && isspace(buf[len-1]))
 164                buf[--len] = '\0';
 165        if (buf[0] == '#' || buf[0] == '\0')
 166                return NULL;
 167        if ((len + 1) % 41)
 168                goto bad_graft_data;
 169        i = (len + 1) / 41 - 1;
 170        graft = xmalloc(sizeof(*graft) + 20 * i);
 171        graft->nr_parent = i;
 172        if (get_sha1_hex(buf, graft->sha1))
 173                goto bad_graft_data;
 174        for (i = 40; i < len; i += 41) {
 175                if (buf[i] != ' ')
 176                        goto bad_graft_data;
 177                if (get_sha1_hex(buf + i + 1, graft->parent[i/41]))
 178                        goto bad_graft_data;
 179        }
 180        return graft;
 181
 182bad_graft_data:
 183        error("bad graft data: %s", buf);
 184        free(graft);
 185        return NULL;
 186}
 187
 188static int read_graft_file(const char *graft_file)
 189{
 190        FILE *fp = fopen(graft_file, "r");
 191        char buf[1024];
 192        if (!fp)
 193                return -1;
 194        while (fgets(buf, sizeof(buf), fp)) {
 195                /* The format is just "Commit Parent1 Parent2 ...\n" */
 196                int len = strlen(buf);
 197                struct commit_graft *graft = read_graft_line(buf, len);
 198                if (!graft)
 199                        continue;
 200                if (register_commit_graft(graft, 1))
 201                        error("duplicate graft data: %s", buf);
 202        }
 203        fclose(fp);
 204        return 0;
 205}
 206
 207static void prepare_commit_graft(void)
 208{
 209        static int commit_graft_prepared;
 210        char *graft_file;
 211
 212        if (commit_graft_prepared)
 213                return;
 214        graft_file = get_graft_file();
 215        read_graft_file(graft_file);
 216        /* make sure shallows are read */
 217        is_repository_shallow();
 218        commit_graft_prepared = 1;
 219}
 220
 221struct commit_graft *lookup_commit_graft(const unsigned char *sha1)
 222{
 223        int pos;
 224        prepare_commit_graft();
 225        pos = commit_graft_pos(sha1);
 226        if (pos < 0)
 227                return NULL;
 228        return commit_graft[pos];
 229}
 230
 231int for_each_commit_graft(each_commit_graft_fn fn, void *cb_data)
 232{
 233        int i, ret;
 234        for (i = ret = 0; i < commit_graft_nr && !ret; i++)
 235                ret = fn(commit_graft[i], cb_data);
 236        return ret;
 237}
 238
 239int unregister_shallow(const unsigned char *sha1)
 240{
 241        int pos = commit_graft_pos(sha1);
 242        if (pos < 0)
 243                return -1;
 244        if (pos + 1 < commit_graft_nr)
 245                memmove(commit_graft + pos, commit_graft + pos + 1,
 246                                sizeof(struct commit_graft *)
 247                                * (commit_graft_nr - pos - 1));
 248        commit_graft_nr--;
 249        return 0;
 250}
 251
 252int parse_commit_buffer(struct commit *item, const void *buffer, unsigned long size)
 253{
 254        const char *tail = buffer;
 255        const char *bufptr = buffer;
 256        unsigned char parent[20];
 257        struct commit_list **pptr;
 258        struct commit_graft *graft;
 259
 260        if (item->object.parsed)
 261                return 0;
 262        item->object.parsed = 1;
 263        tail += size;
 264        if (tail <= bufptr + 46 || memcmp(bufptr, "tree ", 5) || bufptr[45] != '\n')
 265                return error("bogus commit object %s", sha1_to_hex(item->object.sha1));
 266        if (get_sha1_hex(bufptr + 5, parent) < 0)
 267                return error("bad tree pointer in commit %s",
 268                             sha1_to_hex(item->object.sha1));
 269        item->tree = lookup_tree(parent);
 270        bufptr += 46; /* "tree " + "hex sha1" + "\n" */
 271        pptr = &item->parents;
 272
 273        graft = lookup_commit_graft(item->object.sha1);
 274        while (bufptr + 48 < tail && !memcmp(bufptr, "parent ", 7)) {
 275                struct commit *new_parent;
 276
 277                if (tail <= bufptr + 48 ||
 278                    get_sha1_hex(bufptr + 7, parent) ||
 279                    bufptr[47] != '\n')
 280                        return error("bad parents in commit %s", sha1_to_hex(item->object.sha1));
 281                bufptr += 48;
 282                /*
 283                 * The clone is shallow if nr_parent < 0, and we must
 284                 * not traverse its real parents even when we unhide them.
 285                 */
 286                if (graft && (graft->nr_parent < 0 || grafts_replace_parents))
 287                        continue;
 288                new_parent = lookup_commit(parent);
 289                if (new_parent)
 290                        pptr = &commit_list_insert(new_parent, pptr)->next;
 291        }
 292        if (graft) {
 293                int i;
 294                struct commit *new_parent;
 295                for (i = 0; i < graft->nr_parent; i++) {
 296                        new_parent = lookup_commit(graft->parent[i]);
 297                        if (!new_parent)
 298                                continue;
 299                        pptr = &commit_list_insert(new_parent, pptr)->next;
 300                }
 301        }
 302        item->date = parse_commit_date(bufptr, tail);
 303
 304        return 0;
 305}
 306
 307int parse_commit(struct commit *item)
 308{
 309        enum object_type type;
 310        void *buffer;
 311        unsigned long size;
 312        int ret;
 313
 314        if (!item)
 315                return -1;
 316        if (item->object.parsed)
 317                return 0;
 318        buffer = read_sha1_file(item->object.sha1, &type, &size);
 319        if (!buffer)
 320                return error("Could not read %s",
 321                             sha1_to_hex(item->object.sha1));
 322        if (type != OBJ_COMMIT) {
 323                free(buffer);
 324                return error("Object %s not a commit",
 325                             sha1_to_hex(item->object.sha1));
 326        }
 327        ret = parse_commit_buffer(item, buffer, size);
 328        if (save_commit_buffer && !ret) {
 329                item->buffer = buffer;
 330                return 0;
 331        }
 332        free(buffer);
 333        return ret;
 334}
 335
 336int find_commit_subject(const char *commit_buffer, const char **subject)
 337{
 338        const char *eol;
 339        const char *p = commit_buffer;
 340
 341        while (*p && (*p != '\n' || p[1] != '\n'))
 342                p++;
 343        if (*p) {
 344                p += 2;
 345                for (eol = p; *eol && *eol != '\n'; eol++)
 346                        ; /* do nothing */
 347        } else
 348                eol = p;
 349
 350        *subject = p;
 351
 352        return eol - p;
 353}
 354
 355struct commit_list *commit_list_insert(struct commit *item, struct commit_list **list_p)
 356{
 357        struct commit_list *new_list = xmalloc(sizeof(struct commit_list));
 358        new_list->item = item;
 359        new_list->next = *list_p;
 360        *list_p = new_list;
 361        return new_list;
 362}
 363
 364unsigned commit_list_count(const struct commit_list *l)
 365{
 366        unsigned c = 0;
 367        for (; l; l = l->next )
 368                c++;
 369        return c;
 370}
 371
 372void free_commit_list(struct commit_list *list)
 373{
 374        while (list) {
 375                struct commit_list *temp = list;
 376                list = temp->next;
 377                free(temp);
 378        }
 379}
 380
 381struct commit_list * commit_list_insert_by_date(struct commit *item, struct commit_list **list)
 382{
 383        struct commit_list **pp = list;
 384        struct commit_list *p;
 385        while ((p = *pp) != NULL) {
 386                if (p->item->date < item->date) {
 387                        break;
 388                }
 389                pp = &p->next;
 390        }
 391        return commit_list_insert(item, pp);
 392}
 393
 394static int commit_list_compare_by_date(const void *a, const void *b)
 395{
 396        unsigned long a_date = ((const struct commit_list *)a)->item->date;
 397        unsigned long b_date = ((const struct commit_list *)b)->item->date;
 398        if (a_date < b_date)
 399                return 1;
 400        if (a_date > b_date)
 401                return -1;
 402        return 0;
 403}
 404
 405static void *commit_list_get_next(const void *a)
 406{
 407        return ((const struct commit_list *)a)->next;
 408}
 409
 410static void commit_list_set_next(void *a, void *next)
 411{
 412        ((struct commit_list *)a)->next = next;
 413}
 414
 415void commit_list_sort_by_date(struct commit_list **list)
 416{
 417        *list = mergesort(*list, commit_list_get_next, commit_list_set_next,
 418                          commit_list_compare_by_date);
 419}
 420
 421struct commit *pop_most_recent_commit(struct commit_list **list,
 422                                      unsigned int mark)
 423{
 424        struct commit *ret = (*list)->item;
 425        struct commit_list *parents = ret->parents;
 426        struct commit_list *old = *list;
 427
 428        *list = (*list)->next;
 429        free(old);
 430
 431        while (parents) {
 432                struct commit *commit = parents->item;
 433                if (!parse_commit(commit) && !(commit->object.flags & mark)) {
 434                        commit->object.flags |= mark;
 435                        commit_list_insert_by_date(commit, list);
 436                }
 437                parents = parents->next;
 438        }
 439        return ret;
 440}
 441
 442void clear_commit_marks(struct commit *commit, unsigned int mark)
 443{
 444        while (commit) {
 445                struct commit_list *parents;
 446
 447                if (!(mark & commit->object.flags))
 448                        return;
 449
 450                commit->object.flags &= ~mark;
 451
 452                parents = commit->parents;
 453                if (!parents)
 454                        return;
 455
 456                while ((parents = parents->next))
 457                        clear_commit_marks(parents->item, mark);
 458
 459                commit = commit->parents->item;
 460        }
 461}
 462
 463void clear_commit_marks_for_object_array(struct object_array *a, unsigned mark)
 464{
 465        struct object *object;
 466        struct commit *commit;
 467        unsigned int i;
 468
 469        for (i = 0; i < a->nr; i++) {
 470                object = a->objects[i].item;
 471                commit = lookup_commit_reference_gently(object->sha1, 1);
 472                if (commit)
 473                        clear_commit_marks(commit, mark);
 474        }
 475}
 476
 477struct commit *pop_commit(struct commit_list **stack)
 478{
 479        struct commit_list *top = *stack;
 480        struct commit *item = top ? top->item : NULL;
 481
 482        if (top) {
 483                *stack = top->next;
 484                free(top);
 485        }
 486        return item;
 487}
 488
 489/*
 490 * Performs an in-place topological sort on the list supplied.
 491 */
 492void sort_in_topological_order(struct commit_list ** list, int lifo)
 493{
 494        struct commit_list *next, *orig = *list;
 495        struct commit_list *work, **insert;
 496        struct commit_list **pptr;
 497
 498        if (!orig)
 499                return;
 500        *list = NULL;
 501
 502        /* Mark them and clear the indegree */
 503        for (next = orig; next; next = next->next) {
 504                struct commit *commit = next->item;
 505                commit->indegree = 1;
 506        }
 507
 508        /* update the indegree */
 509        for (next = orig; next; next = next->next) {
 510                struct commit_list * parents = next->item->parents;
 511                while (parents) {
 512                        struct commit *parent = parents->item;
 513
 514                        if (parent->indegree)
 515                                parent->indegree++;
 516                        parents = parents->next;
 517                }
 518        }
 519
 520        /*
 521         * find the tips
 522         *
 523         * tips are nodes not reachable from any other node in the list
 524         *
 525         * the tips serve as a starting set for the work queue.
 526         */
 527        work = NULL;
 528        insert = &work;
 529        for (next = orig; next; next = next->next) {
 530                struct commit *commit = next->item;
 531
 532                if (commit->indegree == 1)
 533                        insert = &commit_list_insert(commit, insert)->next;
 534        }
 535
 536        /* process the list in topological order */
 537        if (!lifo)
 538                commit_list_sort_by_date(&work);
 539
 540        pptr = list;
 541        *list = NULL;
 542        while (work) {
 543                struct commit *commit;
 544                struct commit_list *parents, *work_item;
 545
 546                work_item = work;
 547                work = work_item->next;
 548                work_item->next = NULL;
 549
 550                commit = work_item->item;
 551                for (parents = commit->parents; parents ; parents = parents->next) {
 552                        struct commit *parent = parents->item;
 553
 554                        if (!parent->indegree)
 555                                continue;
 556
 557                        /*
 558                         * parents are only enqueued for emission
 559                         * when all their children have been emitted thereby
 560                         * guaranteeing topological order.
 561                         */
 562                        if (--parent->indegree == 1) {
 563                                if (!lifo)
 564                                        commit_list_insert_by_date(parent, &work);
 565                                else
 566                                        commit_list_insert(parent, &work);
 567                        }
 568                }
 569                /*
 570                 * work_item is a commit all of whose children
 571                 * have already been emitted. we can emit it now.
 572                 */
 573                commit->indegree = 0;
 574                *pptr = work_item;
 575                pptr = &work_item->next;
 576        }
 577}
 578
 579/* merge-base stuff */
 580
 581/* bits #0..15 in revision.h */
 582#define PARENT1         (1u<<16)
 583#define PARENT2         (1u<<17)
 584#define STALE           (1u<<18)
 585#define RESULT          (1u<<19)
 586
 587static const unsigned all_flags = (PARENT1 | PARENT2 | STALE | RESULT);
 588
 589static struct commit *interesting(struct commit_list *list)
 590{
 591        while (list) {
 592                struct commit *commit = list->item;
 593                list = list->next;
 594                if (commit->object.flags & STALE)
 595                        continue;
 596                return commit;
 597        }
 598        return NULL;
 599}
 600
 601static struct commit_list *merge_bases_many(struct commit *one, int n, struct commit **twos)
 602{
 603        struct commit_list *list = NULL;
 604        struct commit_list *result = NULL;
 605        int i;
 606
 607        for (i = 0; i < n; i++) {
 608                if (one == twos[i])
 609                        /*
 610                         * We do not mark this even with RESULT so we do not
 611                         * have to clean it up.
 612                         */
 613                        return commit_list_insert(one, &result);
 614        }
 615
 616        if (parse_commit(one))
 617                return NULL;
 618        for (i = 0; i < n; i++) {
 619                if (parse_commit(twos[i]))
 620                        return NULL;
 621        }
 622
 623        one->object.flags |= PARENT1;
 624        commit_list_insert_by_date(one, &list);
 625        for (i = 0; i < n; i++) {
 626                twos[i]->object.flags |= PARENT2;
 627                commit_list_insert_by_date(twos[i], &list);
 628        }
 629
 630        while (interesting(list)) {
 631                struct commit *commit;
 632                struct commit_list *parents;
 633                struct commit_list *next;
 634                int flags;
 635
 636                commit = list->item;
 637                next = list->next;
 638                free(list);
 639                list = next;
 640
 641                flags = commit->object.flags & (PARENT1 | PARENT2 | STALE);
 642                if (flags == (PARENT1 | PARENT2)) {
 643                        if (!(commit->object.flags & RESULT)) {
 644                                commit->object.flags |= RESULT;
 645                                commit_list_insert_by_date(commit, &result);
 646                        }
 647                        /* Mark parents of a found merge stale */
 648                        flags |= STALE;
 649                }
 650                parents = commit->parents;
 651                while (parents) {
 652                        struct commit *p = parents->item;
 653                        parents = parents->next;
 654                        if ((p->object.flags & flags) == flags)
 655                                continue;
 656                        if (parse_commit(p))
 657                                return NULL;
 658                        p->object.flags |= flags;
 659                        commit_list_insert_by_date(p, &list);
 660                }
 661        }
 662
 663        /* Clean up the result to remove stale ones */
 664        free_commit_list(list);
 665        list = result; result = NULL;
 666        while (list) {
 667                struct commit_list *next = list->next;
 668                if (!(list->item->object.flags & STALE))
 669                        commit_list_insert_by_date(list->item, &result);
 670                free(list);
 671                list = next;
 672        }
 673        return result;
 674}
 675
 676struct commit_list *get_octopus_merge_bases(struct commit_list *in)
 677{
 678        struct commit_list *i, *j, *k, *ret = NULL;
 679        struct commit_list **pptr = &ret;
 680
 681        for (i = in; i; i = i->next) {
 682                if (!ret)
 683                        pptr = &commit_list_insert(i->item, pptr)->next;
 684                else {
 685                        struct commit_list *new = NULL, *end = NULL;
 686
 687                        for (j = ret; j; j = j->next) {
 688                                struct commit_list *bases;
 689                                bases = get_merge_bases(i->item, j->item, 1);
 690                                if (!new)
 691                                        new = bases;
 692                                else
 693                                        end->next = bases;
 694                                for (k = bases; k; k = k->next)
 695                                        end = k;
 696                        }
 697                        ret = new;
 698                }
 699        }
 700        return ret;
 701}
 702
 703struct commit_list *get_merge_bases_many(struct commit *one,
 704                                         int n,
 705                                         struct commit **twos,
 706                                         int cleanup)
 707{
 708        struct commit_list *list;
 709        struct commit **rslt;
 710        struct commit_list *result;
 711        int cnt, i, j;
 712
 713        result = merge_bases_many(one, n, twos);
 714        for (i = 0; i < n; i++) {
 715                if (one == twos[i])
 716                        return result;
 717        }
 718        if (!result || !result->next) {
 719                if (cleanup) {
 720                        clear_commit_marks(one, all_flags);
 721                        for (i = 0; i < n; i++)
 722                                clear_commit_marks(twos[i], all_flags);
 723                }
 724                return result;
 725        }
 726
 727        /* There are more than one */
 728        cnt = 0;
 729        list = result;
 730        while (list) {
 731                list = list->next;
 732                cnt++;
 733        }
 734        rslt = xcalloc(cnt, sizeof(*rslt));
 735        for (list = result, i = 0; list; list = list->next)
 736                rslt[i++] = list->item;
 737        free_commit_list(result);
 738
 739        clear_commit_marks(one, all_flags);
 740        for (i = 0; i < n; i++)
 741                clear_commit_marks(twos[i], all_flags);
 742        for (i = 0; i < cnt - 1; i++) {
 743                for (j = i+1; j < cnt; j++) {
 744                        if (!rslt[i] || !rslt[j])
 745                                continue;
 746                        result = merge_bases_many(rslt[i], 1, &rslt[j]);
 747                        clear_commit_marks(rslt[i], all_flags);
 748                        clear_commit_marks(rslt[j], all_flags);
 749                        for (list = result; list; list = list->next) {
 750                                if (rslt[i] == list->item)
 751                                        rslt[i] = NULL;
 752                                if (rslt[j] == list->item)
 753                                        rslt[j] = NULL;
 754                        }
 755                }
 756        }
 757
 758        /* Surviving ones in rslt[] are the independent results */
 759        result = NULL;
 760        for (i = 0; i < cnt; i++) {
 761                if (rslt[i])
 762                        commit_list_insert_by_date(rslt[i], &result);
 763        }
 764        free(rslt);
 765        return result;
 766}
 767
 768struct commit_list *get_merge_bases(struct commit *one, struct commit *two,
 769                                    int cleanup)
 770{
 771        return get_merge_bases_many(one, 1, &two, cleanup);
 772}
 773
 774int is_descendant_of(struct commit *commit, struct commit_list *with_commit)
 775{
 776        if (!with_commit)
 777                return 1;
 778        while (with_commit) {
 779                struct commit *other;
 780
 781                other = with_commit->item;
 782                with_commit = with_commit->next;
 783                if (in_merge_bases(other, &commit, 1))
 784                        return 1;
 785        }
 786        return 0;
 787}
 788
 789int in_merge_bases(struct commit *commit, struct commit **reference, int num)
 790{
 791        struct commit_list *bases, *b;
 792        int ret = 0;
 793
 794        if (num == 1)
 795                bases = get_merge_bases(commit, *reference, 1);
 796        else
 797                die("not yet");
 798        for (b = bases; b; b = b->next) {
 799                if (!hashcmp(commit->object.sha1, b->item->object.sha1)) {
 800                        ret = 1;
 801                        break;
 802                }
 803        }
 804
 805        free_commit_list(bases);
 806        return ret;
 807}
 808
 809struct commit_list *reduce_heads(struct commit_list *heads)
 810{
 811        struct commit_list *p;
 812        struct commit_list *result = NULL, **tail = &result;
 813        struct commit **other;
 814        size_t num_head, num_other;
 815
 816        if (!heads)
 817                return NULL;
 818
 819        /* Avoid unnecessary reallocations */
 820        for (p = heads, num_head = 0; p; p = p->next)
 821                num_head++;
 822        other = xcalloc(sizeof(*other), num_head);
 823
 824        /* For each commit, see if it can be reached by others */
 825        for (p = heads; p; p = p->next) {
 826                struct commit_list *q, *base;
 827
 828                /* Do we already have this in the result? */
 829                for (q = result; q; q = q->next)
 830                        if (p->item == q->item)
 831                                break;
 832                if (q)
 833                        continue;
 834
 835                num_other = 0;
 836                for (q = heads; q; q = q->next) {
 837                        if (p->item == q->item)
 838                                continue;
 839                        other[num_other++] = q->item;
 840                }
 841                if (num_other)
 842                        base = get_merge_bases_many(p->item, num_other, other, 1);
 843                else
 844                        base = NULL;
 845                /*
 846                 * If p->item does not have anything common with other
 847                 * commits, there won't be any merge base.  If it is
 848                 * reachable from some of the others, p->item will be
 849                 * the merge base.  If its history is connected with
 850                 * others, but p->item is not reachable by others, we
 851                 * will get something other than p->item back.
 852                 */
 853                if (!base || (base->item != p->item))
 854                        tail = &(commit_list_insert(p->item, tail)->next);
 855                free_commit_list(base);
 856        }
 857        free(other);
 858        return result;
 859}
 860
 861static const char gpg_sig_header[] = "gpgsig";
 862static const int gpg_sig_header_len = sizeof(gpg_sig_header) - 1;
 863
 864static int do_sign_commit(struct strbuf *buf, const char *keyid)
 865{
 866        struct strbuf sig = STRBUF_INIT;
 867        int inspos, copypos;
 868
 869        /* find the end of the header */
 870        inspos = strstr(buf->buf, "\n\n") - buf->buf + 1;
 871
 872        if (!keyid || !*keyid)
 873                keyid = get_signing_key();
 874        if (sign_buffer(buf, &sig, keyid)) {
 875                strbuf_release(&sig);
 876                return -1;
 877        }
 878
 879        for (copypos = 0; sig.buf[copypos]; ) {
 880                const char *bol = sig.buf + copypos;
 881                const char *eol = strchrnul(bol, '\n');
 882                int len = (eol - bol) + !!*eol;
 883
 884                if (!copypos) {
 885                        strbuf_insert(buf, inspos, gpg_sig_header, gpg_sig_header_len);
 886                        inspos += gpg_sig_header_len;
 887                }
 888                strbuf_insert(buf, inspos++, " ", 1);
 889                strbuf_insert(buf, inspos, bol, len);
 890                inspos += len;
 891                copypos += len;
 892        }
 893        strbuf_release(&sig);
 894        return 0;
 895}
 896
 897int parse_signed_commit(const unsigned char *sha1,
 898                        struct strbuf *payload, struct strbuf *signature)
 899{
 900        unsigned long size;
 901        enum object_type type;
 902        char *buffer = read_sha1_file(sha1, &type, &size);
 903        int in_signature, saw_signature = -1;
 904        char *line, *tail;
 905
 906        if (!buffer || type != OBJ_COMMIT)
 907                goto cleanup;
 908
 909        line = buffer;
 910        tail = buffer + size;
 911        in_signature = 0;
 912        saw_signature = 0;
 913        while (line < tail) {
 914                const char *sig = NULL;
 915                char *next = memchr(line, '\n', tail - line);
 916
 917                next = next ? next + 1 : tail;
 918                if (in_signature && line[0] == ' ')
 919                        sig = line + 1;
 920                else if (!prefixcmp(line, gpg_sig_header) &&
 921                         line[gpg_sig_header_len] == ' ')
 922                        sig = line + gpg_sig_header_len + 1;
 923                if (sig) {
 924                        strbuf_add(signature, sig, next - sig);
 925                        saw_signature = 1;
 926                        in_signature = 1;
 927                } else {
 928                        if (*line == '\n')
 929                                /* dump the whole remainder of the buffer */
 930                                next = tail;
 931                        strbuf_add(payload, line, next - line);
 932                        in_signature = 0;
 933                }
 934                line = next;
 935        }
 936 cleanup:
 937        free(buffer);
 938        return saw_signature;
 939}
 940
 941static void handle_signed_tag(struct commit *parent, struct commit_extra_header ***tail)
 942{
 943        struct merge_remote_desc *desc;
 944        struct commit_extra_header *mergetag;
 945        char *buf;
 946        unsigned long size, len;
 947        enum object_type type;
 948
 949        desc = merge_remote_util(parent);
 950        if (!desc || !desc->obj)
 951                return;
 952        buf = read_sha1_file(desc->obj->sha1, &type, &size);
 953        if (!buf || type != OBJ_TAG)
 954                goto free_return;
 955        len = parse_signature(buf, size);
 956        if (size == len)
 957                goto free_return;
 958        /*
 959         * We could verify this signature and either omit the tag when
 960         * it does not validate, but the integrator may not have the
 961         * public key of the signer of the tag he is merging, while a
 962         * later auditor may have it while auditing, so let's not run
 963         * verify-signed-buffer here for now...
 964         *
 965         * if (verify_signed_buffer(buf, len, buf + len, size - len, ...))
 966         *      warn("warning: signed tag unverified.");
 967         */
 968        mergetag = xcalloc(1, sizeof(*mergetag));
 969        mergetag->key = xstrdup("mergetag");
 970        mergetag->value = buf;
 971        mergetag->len = size;
 972
 973        **tail = mergetag;
 974        *tail = &mergetag->next;
 975        return;
 976
 977free_return:
 978        free(buf);
 979}
 980
 981void append_merge_tag_headers(struct commit_list *parents,
 982                              struct commit_extra_header ***tail)
 983{
 984        while (parents) {
 985                struct commit *parent = parents->item;
 986                handle_signed_tag(parent, tail);
 987                parents = parents->next;
 988        }
 989}
 990
 991static void add_extra_header(struct strbuf *buffer,
 992                             struct commit_extra_header *extra)
 993{
 994        strbuf_addstr(buffer, extra->key);
 995        if (extra->len)
 996                strbuf_add_lines(buffer, " ", extra->value, extra->len);
 997        else
 998                strbuf_addch(buffer, '\n');
 999}
1000
1001struct commit_extra_header *read_commit_extra_headers(struct commit *commit,
1002                                                      const char **exclude)
1003{
1004        struct commit_extra_header *extra = NULL;
1005        unsigned long size;
1006        enum object_type type;
1007        char *buffer = read_sha1_file(commit->object.sha1, &type, &size);
1008        if (buffer && type == OBJ_COMMIT)
1009                extra = read_commit_extra_header_lines(buffer, size, exclude);
1010        free(buffer);
1011        return extra;
1012}
1013
1014static inline int standard_header_field(const char *field, size_t len)
1015{
1016        return ((len == 4 && !memcmp(field, "tree ", 5)) ||
1017                (len == 6 && !memcmp(field, "parent ", 7)) ||
1018                (len == 6 && !memcmp(field, "author ", 7)) ||
1019                (len == 9 && !memcmp(field, "committer ", 10)) ||
1020                (len == 8 && !memcmp(field, "encoding ", 9)));
1021}
1022
1023static int excluded_header_field(const char *field, size_t len, const char **exclude)
1024{
1025        if (!exclude)
1026                return 0;
1027
1028        while (*exclude) {
1029                size_t xlen = strlen(*exclude);
1030                if (len == xlen &&
1031                    !memcmp(field, *exclude, xlen) && field[xlen] == ' ')
1032                        return 1;
1033                exclude++;
1034        }
1035        return 0;
1036}
1037
1038struct commit_extra_header *read_commit_extra_header_lines(const char *buffer, size_t size,
1039                                                           const char **exclude)
1040{
1041        struct commit_extra_header *extra = NULL, **tail = &extra, *it = NULL;
1042        const char *line, *next, *eof, *eob;
1043        struct strbuf buf = STRBUF_INIT;
1044
1045        for (line = buffer, eob = line + size;
1046             line < eob && *line != '\n';
1047             line = next) {
1048                next = memchr(line, '\n', eob - line);
1049                next = next ? next + 1 : eob;
1050                if (*line == ' ') {
1051                        /* continuation */
1052                        if (it)
1053                                strbuf_add(&buf, line + 1, next - (line + 1));
1054                        continue;
1055                }
1056                if (it)
1057                        it->value = strbuf_detach(&buf, &it->len);
1058                strbuf_reset(&buf);
1059                it = NULL;
1060
1061                eof = strchr(line, ' ');
1062                if (next <= eof)
1063                        eof = next;
1064
1065                if (standard_header_field(line, eof - line) ||
1066                    excluded_header_field(line, eof - line, exclude))
1067                        continue;
1068
1069                it = xcalloc(1, sizeof(*it));
1070                it->key = xmemdupz(line, eof-line);
1071                *tail = it;
1072                tail = &it->next;
1073                if (eof + 1 < next)
1074                        strbuf_add(&buf, eof + 1, next - (eof + 1));
1075        }
1076        if (it)
1077                it->value = strbuf_detach(&buf, &it->len);
1078        return extra;
1079}
1080
1081void free_commit_extra_headers(struct commit_extra_header *extra)
1082{
1083        while (extra) {
1084                struct commit_extra_header *next = extra->next;
1085                free(extra->key);
1086                free(extra->value);
1087                free(extra);
1088                extra = next;
1089        }
1090}
1091
1092int commit_tree(const struct strbuf *msg, unsigned char *tree,
1093                struct commit_list *parents, unsigned char *ret,
1094                const char *author, const char *sign_commit)
1095{
1096        struct commit_extra_header *extra = NULL, **tail = &extra;
1097        int result;
1098
1099        append_merge_tag_headers(parents, &tail);
1100        result = commit_tree_extended(msg, tree, parents, ret,
1101                                      author, sign_commit, extra);
1102        free_commit_extra_headers(extra);
1103        return result;
1104}
1105
1106static const char commit_utf8_warn[] =
1107"Warning: commit message does not conform to UTF-8.\n"
1108"You may want to amend it after fixing the message, or set the config\n"
1109"variable i18n.commitencoding to the encoding your project uses.\n";
1110
1111int commit_tree_extended(const struct strbuf *msg, unsigned char *tree,
1112                         struct commit_list *parents, unsigned char *ret,
1113                         const char *author, const char *sign_commit,
1114                         struct commit_extra_header *extra)
1115{
1116        int result;
1117        int encoding_is_utf8;
1118        struct strbuf buffer;
1119
1120        assert_sha1_type(tree, OBJ_TREE);
1121
1122        if (memchr(msg->buf, '\0', msg->len))
1123                return error("a NUL byte in commit log message not allowed.");
1124
1125        /* Not having i18n.commitencoding is the same as having utf-8 */
1126        encoding_is_utf8 = is_encoding_utf8(git_commit_encoding);
1127
1128        strbuf_init(&buffer, 8192); /* should avoid reallocs for the headers */
1129        strbuf_addf(&buffer, "tree %s\n", sha1_to_hex(tree));
1130
1131        /*
1132         * NOTE! This ordering means that the same exact tree merged with a
1133         * different order of parents will be a _different_ changeset even
1134         * if everything else stays the same.
1135         */
1136        while (parents) {
1137                struct commit_list *next = parents->next;
1138                struct commit *parent = parents->item;
1139
1140                strbuf_addf(&buffer, "parent %s\n",
1141                            sha1_to_hex(parent->object.sha1));
1142                free(parents);
1143                parents = next;
1144        }
1145
1146        /* Person/date information */
1147        if (!author)
1148                author = git_author_info(IDENT_ERROR_ON_NO_NAME);
1149        strbuf_addf(&buffer, "author %s\n", author);
1150        strbuf_addf(&buffer, "committer %s\n", git_committer_info(IDENT_ERROR_ON_NO_NAME));
1151        if (!encoding_is_utf8)
1152                strbuf_addf(&buffer, "encoding %s\n", git_commit_encoding);
1153
1154        while (extra) {
1155                add_extra_header(&buffer, extra);
1156                extra = extra->next;
1157        }
1158        strbuf_addch(&buffer, '\n');
1159
1160        /* And add the comment */
1161        strbuf_addbuf(&buffer, msg);
1162
1163        /* And check the encoding */
1164        if (encoding_is_utf8 && !is_utf8(buffer.buf))
1165                fprintf(stderr, commit_utf8_warn);
1166
1167        if (sign_commit && do_sign_commit(&buffer, sign_commit))
1168                return -1;
1169
1170        result = write_sha1_file(buffer.buf, buffer.len, commit_type, ret);
1171        strbuf_release(&buffer);
1172        return result;
1173}
1174
1175struct commit *get_merge_parent(const char *name)
1176{
1177        struct object *obj;
1178        struct commit *commit;
1179        unsigned char sha1[20];
1180        if (get_sha1(name, sha1))
1181                return NULL;
1182        obj = parse_object(sha1);
1183        commit = (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
1184        if (commit && !commit->util) {
1185                struct merge_remote_desc *desc;
1186                desc = xmalloc(sizeof(*desc));
1187                desc->obj = obj;
1188                desc->name = strdup(name);
1189                commit->util = desc;
1190        }
1191        return commit;
1192}