a608faf23217fadd42105d9eab96b28474930b69
   1#include "cache.h"
   2#include "tag.h"
   3#include "commit.h"
   4
   5int save_commit_buffer = 1;
   6
   7struct sort_node
   8{
   9        /*
  10         * the number of children of the associated commit
  11         * that also occur in the list being sorted.
  12         */
  13        unsigned int indegree;
  14
  15        /*
  16         * reference to original list item that we will re-use
  17         * on output.
  18         */
  19        struct commit_list * list_item;
  20
  21};
  22
  23const char *commit_type = "commit";
  24
  25struct cmt_fmt_map {
  26        const char *n;
  27        size_t cmp_len;
  28        enum cmit_fmt v;
  29} cmt_fmts[] = {
  30        { "raw",        1,      CMIT_FMT_RAW },
  31        { "medium",     1,      CMIT_FMT_MEDIUM },
  32        { "short",      1,      CMIT_FMT_SHORT },
  33        { "email",      1,      CMIT_FMT_EMAIL },
  34        { "full",       5,      CMIT_FMT_FULL },
  35        { "fuller",     5,      CMIT_FMT_FULLER },
  36        { "oneline",    1,      CMIT_FMT_ONELINE },
  37};
  38
  39enum cmit_fmt get_commit_format(const char *arg)
  40{
  41        int i;
  42
  43        if (!arg || !*arg)
  44                return CMIT_FMT_DEFAULT;
  45        if (*arg == '=')
  46                arg++;
  47        for (i = 0; i < ARRAY_SIZE(cmt_fmts); i++) {
  48                if (!strncmp(arg, cmt_fmts[i].n, cmt_fmts[i].cmp_len))
  49                        return cmt_fmts[i].v;
  50        }
  51
  52        die("invalid --pretty format: %s", arg);
  53}
  54
  55static struct commit *check_commit(struct object *obj,
  56                                   const unsigned char *sha1,
  57                                   int quiet)
  58{
  59        if (obj->type != TYPE_COMMIT) {
  60                if (!quiet)
  61                        error("Object %s is a %s, not a commit",
  62                              sha1_to_hex(sha1), typename(obj->type));
  63                return NULL;
  64        }
  65        return (struct commit *) obj;
  66}
  67
  68struct commit *lookup_commit_reference_gently(const unsigned char *sha1,
  69                                              int quiet)
  70{
  71        struct object *obj = deref_tag(parse_object(sha1), NULL, 0);
  72
  73        if (!obj)
  74                return NULL;
  75        return check_commit(obj, sha1, quiet);
  76}
  77
  78struct commit *lookup_commit_reference(const unsigned char *sha1)
  79{
  80        return lookup_commit_reference_gently(sha1, 0);
  81}
  82
  83struct commit *lookup_commit(const unsigned char *sha1)
  84{
  85        struct object *obj = lookup_object(sha1);
  86        if (!obj) {
  87                struct commit *ret = alloc_commit_node();
  88                created_object(sha1, &ret->object);
  89                ret->object.type = TYPE_COMMIT;
  90                return ret;
  91        }
  92        if (!obj->type)
  93                obj->type = TYPE_COMMIT;
  94        return check_commit(obj, sha1, 0);
  95}
  96
  97static unsigned long parse_commit_date(const char *buf)
  98{
  99        unsigned long date;
 100
 101        if (memcmp(buf, "author", 6))
 102                return 0;
 103        while (*buf++ != '\n')
 104                /* nada */;
 105        if (memcmp(buf, "committer", 9))
 106                return 0;
 107        while (*buf++ != '>')
 108                /* nada */;
 109        date = strtoul(buf, NULL, 10);
 110        if (date == ULONG_MAX)
 111                date = 0;
 112        return date;
 113}
 114
 115static struct commit_graft **commit_graft;
 116static int commit_graft_alloc, commit_graft_nr;
 117
 118static int commit_graft_pos(const unsigned char *sha1)
 119{
 120        int lo, hi;
 121        lo = 0;
 122        hi = commit_graft_nr;
 123        while (lo < hi) {
 124                int mi = (lo + hi) / 2;
 125                struct commit_graft *graft = commit_graft[mi];
 126                int cmp = memcmp(sha1, graft->sha1, 20);
 127                if (!cmp)
 128                        return mi;
 129                if (cmp < 0)
 130                        hi = mi;
 131                else
 132                        lo = mi + 1;
 133        }
 134        return -lo - 1;
 135}
 136
 137int register_commit_graft(struct commit_graft *graft, int ignore_dups)
 138{
 139        int pos = commit_graft_pos(graft->sha1);
 140        
 141        if (0 <= pos) {
 142                if (ignore_dups)
 143                        free(graft);
 144                else {
 145                        free(commit_graft[pos]);
 146                        commit_graft[pos] = graft;
 147                }
 148                return 1;
 149        }
 150        pos = -pos - 1;
 151        if (commit_graft_alloc <= ++commit_graft_nr) {
 152                commit_graft_alloc = alloc_nr(commit_graft_alloc);
 153                commit_graft = xrealloc(commit_graft,
 154                                        sizeof(*commit_graft) *
 155                                        commit_graft_alloc);
 156        }
 157        if (pos < commit_graft_nr)
 158                memmove(commit_graft + pos + 1,
 159                        commit_graft + pos,
 160                        (commit_graft_nr - pos - 1) *
 161                        sizeof(*commit_graft));
 162        commit_graft[pos] = graft;
 163        return 0;
 164}
 165
 166struct commit_graft *read_graft_line(char *buf, int len)
 167{
 168        /* The format is just "Commit Parent1 Parent2 ...\n" */
 169        int i;
 170        struct commit_graft *graft = NULL;
 171
 172        if (buf[len-1] == '\n')
 173                buf[--len] = 0;
 174        if (buf[0] == '#' || buf[0] == '\0')
 175                return NULL;
 176        if ((len + 1) % 41) {
 177        bad_graft_data:
 178                error("bad graft data: %s", buf);
 179                free(graft);
 180                return NULL;
 181        }
 182        i = (len + 1) / 41 - 1;
 183        graft = xmalloc(sizeof(*graft) + 20 * i);
 184        graft->nr_parent = i;
 185        if (get_sha1_hex(buf, graft->sha1))
 186                goto bad_graft_data;
 187        for (i = 40; i < len; i += 41) {
 188                if (buf[i] != ' ')
 189                        goto bad_graft_data;
 190                if (get_sha1_hex(buf + i + 1, graft->parent[i/41]))
 191                        goto bad_graft_data;
 192        }
 193        return graft;
 194}
 195
 196int read_graft_file(const char *graft_file)
 197{
 198        FILE *fp = fopen(graft_file, "r");
 199        char buf[1024];
 200        if (!fp)
 201                return -1;
 202        while (fgets(buf, sizeof(buf), fp)) {
 203                /* The format is just "Commit Parent1 Parent2 ...\n" */
 204                int len = strlen(buf);
 205                struct commit_graft *graft = read_graft_line(buf, len);
 206                if (!graft)
 207                        continue;
 208                if (register_commit_graft(graft, 1))
 209                        error("duplicate graft data: %s", buf);
 210        }
 211        fclose(fp);
 212        return 0;
 213}
 214
 215static void prepare_commit_graft(void)
 216{
 217        static int commit_graft_prepared;
 218        char *graft_file;
 219
 220        if (commit_graft_prepared)
 221                return;
 222        graft_file = get_graft_file();
 223        read_graft_file(graft_file);
 224        commit_graft_prepared = 1;
 225}
 226
 227static struct commit_graft *lookup_commit_graft(const unsigned char *sha1)
 228{
 229        int pos;
 230        prepare_commit_graft();
 231        pos = commit_graft_pos(sha1);
 232        if (pos < 0)
 233                return NULL;
 234        return commit_graft[pos];
 235}
 236
 237int parse_commit_buffer(struct commit *item, void *buffer, unsigned long size)
 238{
 239        char *tail = buffer;
 240        char *bufptr = buffer;
 241        unsigned char parent[20];
 242        struct commit_list **pptr;
 243        struct commit_graft *graft;
 244        unsigned n_refs = 0;
 245
 246        if (item->object.parsed)
 247                return 0;
 248        item->object.parsed = 1;
 249        tail += size;
 250        if (tail <= bufptr + 5 || memcmp(bufptr, "tree ", 5))
 251                return error("bogus commit object %s", sha1_to_hex(item->object.sha1));
 252        if (tail <= bufptr + 45 || get_sha1_hex(bufptr + 5, parent) < 0)
 253                return error("bad tree pointer in commit %s",
 254                             sha1_to_hex(item->object.sha1));
 255        item->tree = lookup_tree(parent);
 256        if (item->tree)
 257                n_refs++;
 258        bufptr += 46; /* "tree " + "hex sha1" + "\n" */
 259        pptr = &item->parents;
 260
 261        graft = lookup_commit_graft(item->object.sha1);
 262        while (bufptr + 48 < tail && !memcmp(bufptr, "parent ", 7)) {
 263                struct commit *new_parent;
 264
 265                if (tail <= bufptr + 48 ||
 266                    get_sha1_hex(bufptr + 7, parent) ||
 267                    bufptr[47] != '\n')
 268                        return error("bad parents in commit %s", sha1_to_hex(item->object.sha1));
 269                bufptr += 48;
 270                if (graft)
 271                        continue;
 272                new_parent = lookup_commit(parent);
 273                if (new_parent) {
 274                        pptr = &commit_list_insert(new_parent, pptr)->next;
 275                        n_refs++;
 276                }
 277        }
 278        if (graft) {
 279                int i;
 280                struct commit *new_parent;
 281                for (i = 0; i < graft->nr_parent; i++) {
 282                        new_parent = lookup_commit(graft->parent[i]);
 283                        if (!new_parent)
 284                                continue;
 285                        pptr = &commit_list_insert(new_parent, pptr)->next;
 286                        n_refs++;
 287                }
 288        }
 289        item->date = parse_commit_date(bufptr);
 290
 291        if (track_object_refs) {
 292                unsigned i = 0;
 293                struct commit_list *p;
 294                struct object_refs *refs = alloc_object_refs(n_refs);
 295                if (item->tree)
 296                        refs->ref[i++] = &item->tree->object;
 297                for (p = item->parents; p; p = p->next)
 298                        refs->ref[i++] = &p->item->object;
 299                set_object_refs(&item->object, refs);
 300        }
 301
 302        return 0;
 303}
 304
 305int parse_commit(struct commit *item)
 306{
 307        char type[20];
 308        void *buffer;
 309        unsigned long size;
 310        int ret;
 311
 312        if (item->object.parsed)
 313                return 0;
 314        buffer = read_sha1_file(item->object.sha1, type, &size);
 315        if (!buffer)
 316                return error("Could not read %s",
 317                             sha1_to_hex(item->object.sha1));
 318        if (strcmp(type, commit_type)) {
 319                free(buffer);
 320                return error("Object %s not a commit",
 321                             sha1_to_hex(item->object.sha1));
 322        }
 323        ret = parse_commit_buffer(item, buffer, size);
 324        if (save_commit_buffer && !ret) {
 325                item->buffer = buffer;
 326                return 0;
 327        }
 328        free(buffer);
 329        return ret;
 330}
 331
 332struct commit_list *commit_list_insert(struct commit *item, struct commit_list **list_p)
 333{
 334        struct commit_list *new_list = xmalloc(sizeof(struct commit_list));
 335        new_list->item = item;
 336        new_list->next = *list_p;
 337        *list_p = new_list;
 338        return new_list;
 339}
 340
 341void free_commit_list(struct commit_list *list)
 342{
 343        while (list) {
 344                struct commit_list *temp = list;
 345                list = temp->next;
 346                free(temp);
 347        }
 348}
 349
 350struct commit_list * insert_by_date(struct commit *item, struct commit_list **list)
 351{
 352        struct commit_list **pp = list;
 353        struct commit_list *p;
 354        while ((p = *pp) != NULL) {
 355                if (p->item->date < item->date) {
 356                        break;
 357                }
 358                pp = &p->next;
 359        }
 360        return commit_list_insert(item, pp);
 361}
 362
 363        
 364void sort_by_date(struct commit_list **list)
 365{
 366        struct commit_list *ret = NULL;
 367        while (*list) {
 368                insert_by_date((*list)->item, &ret);
 369                *list = (*list)->next;
 370        }
 371        *list = ret;
 372}
 373
 374struct commit *pop_most_recent_commit(struct commit_list **list,
 375                                      unsigned int mark)
 376{
 377        struct commit *ret = (*list)->item;
 378        struct commit_list *parents = ret->parents;
 379        struct commit_list *old = *list;
 380
 381        *list = (*list)->next;
 382        free(old);
 383
 384        while (parents) {
 385                struct commit *commit = parents->item;
 386                parse_commit(commit);
 387                if (!(commit->object.flags & mark)) {
 388                        commit->object.flags |= mark;
 389                        insert_by_date(commit, list);
 390                }
 391                parents = parents->next;
 392        }
 393        return ret;
 394}
 395
 396void clear_commit_marks(struct commit *commit, unsigned int mark)
 397{
 398        struct commit_list *parents;
 399
 400        if (!commit)
 401                return;
 402        parents = commit->parents;
 403        commit->object.flags &= ~mark;
 404        while (parents) {
 405                clear_commit_marks(parents->item, mark);
 406                parents = parents->next;
 407        }
 408}
 409
 410/*
 411 * Generic support for pretty-printing the header
 412 */
 413static int get_one_line(const char *msg, unsigned long len)
 414{
 415        int ret = 0;
 416
 417        while (len--) {
 418                char c = *msg++;
 419                if (!c)
 420                        break;
 421                ret++;
 422                if (c == '\n')
 423                        break;
 424        }
 425        return ret;
 426}
 427
 428static int is_rfc2047_special(char ch)
 429{
 430        return ((ch & 0x80) || (ch == '=') || (ch == '?') || (ch == '_'));
 431}
 432
 433static int add_rfc2047(char *buf, const char *line, int len)
 434{
 435        char *bp = buf;
 436        int i, needquote;
 437        static const char q_utf8[] = "=?utf-8?q?";
 438
 439        for (i = needquote = 0; !needquote && i < len; i++) {
 440                unsigned ch = line[i];
 441                if (ch & 0x80)
 442                        needquote++;
 443                if ((i + 1 < len) &&
 444                    (ch == '=' && line[i+1] == '?'))
 445                        needquote++;
 446        }
 447        if (!needquote)
 448                return sprintf(buf, "%.*s", len, line);
 449
 450        memcpy(bp, q_utf8, sizeof(q_utf8)-1);
 451        bp += sizeof(q_utf8)-1;
 452        for (i = 0; i < len; i++) {
 453                unsigned ch = line[i] & 0xFF;
 454                if (is_rfc2047_special(ch)) {
 455                        sprintf(bp, "=%02X", ch);
 456                        bp += 3;
 457                }
 458                else if (ch == ' ')
 459                        *bp++ = '_';
 460                else
 461                        *bp++ = ch;
 462        }
 463        memcpy(bp, "?=", 2);
 464        bp += 2;
 465        return bp - buf;
 466}
 467
 468static int add_user_info(const char *what, enum cmit_fmt fmt, char *buf, const char *line)
 469{
 470        char *date;
 471        int namelen;
 472        unsigned long time;
 473        int tz, ret;
 474        const char *filler = "    ";
 475
 476        if (fmt == CMIT_FMT_ONELINE)
 477                return 0;
 478        date = strchr(line, '>');
 479        if (!date)
 480                return 0;
 481        namelen = ++date - line;
 482        time = strtoul(date, &date, 10);
 483        tz = strtol(date, NULL, 10);
 484
 485        if (fmt == CMIT_FMT_EMAIL) {
 486                char *name_tail = strchr(line, '<');
 487                int display_name_length;
 488                if (!name_tail)
 489                        return 0;
 490                while (line < name_tail && isspace(name_tail[-1]))
 491                        name_tail--;
 492                display_name_length = name_tail - line;
 493                filler = "";
 494                strcpy(buf, "From: ");
 495                ret = strlen(buf);
 496                ret += add_rfc2047(buf + ret, line, display_name_length);
 497                memcpy(buf + ret, name_tail, namelen - display_name_length);
 498                ret += namelen - display_name_length;
 499                buf[ret++] = '\n';
 500        }
 501        else {
 502                ret = sprintf(buf, "%s: %.*s%.*s\n", what,
 503                              (fmt == CMIT_FMT_FULLER) ? 4 : 0,
 504                              filler, namelen, line);
 505        }
 506        switch (fmt) {
 507        case CMIT_FMT_MEDIUM:
 508                ret += sprintf(buf + ret, "Date:   %s\n", show_date(time, tz));
 509                break;
 510        case CMIT_FMT_EMAIL:
 511                ret += sprintf(buf + ret, "Date: %s\n",
 512                               show_rfc2822_date(time, tz));
 513                break;
 514        case CMIT_FMT_FULLER:
 515                ret += sprintf(buf + ret, "%sDate: %s\n", what, show_date(time, tz));
 516                break;
 517        default:
 518                /* notin' */
 519                break;
 520        }
 521        return ret;
 522}
 523
 524static int is_empty_line(const char *line, int *len_p)
 525{
 526        int len = *len_p;
 527        while (len && isspace(line[len-1]))
 528                len--;
 529        *len_p = len;
 530        return !len;
 531}
 532
 533static int add_merge_info(enum cmit_fmt fmt, char *buf, const struct commit *commit, int abbrev)
 534{
 535        struct commit_list *parent = commit->parents;
 536        int offset;
 537
 538        if ((fmt == CMIT_FMT_ONELINE) || (fmt == CMIT_FMT_EMAIL) ||
 539            !parent || !parent->next)
 540                return 0;
 541
 542        offset = sprintf(buf, "Merge:");
 543
 544        while (parent) {
 545                struct commit *p = parent->item;
 546                const char *hex = abbrev
 547                        ? find_unique_abbrev(p->object.sha1, abbrev)
 548                        : sha1_to_hex(p->object.sha1);
 549                const char *dots = (abbrev && strlen(hex) != 40) ? "..." : "";
 550                parent = parent->next;
 551
 552                offset += sprintf(buf + offset, " %s%s", hex, dots);
 553        }
 554        buf[offset++] = '\n';
 555        return offset;
 556}
 557
 558unsigned long pretty_print_commit(enum cmit_fmt fmt, const struct commit *commit, unsigned long len, char *buf, unsigned long space, int abbrev, const char *subject, const char *after_subject)
 559{
 560        int hdr = 1, body = 0;
 561        unsigned long offset = 0;
 562        int indent = 4;
 563        int parents_shown = 0;
 564        const char *msg = commit->buffer;
 565        int plain_non_ascii = 0;
 566
 567        if (fmt == CMIT_FMT_ONELINE || fmt == CMIT_FMT_EMAIL)
 568                indent = 0;
 569
 570        /* After-subject is used to pass in Content-Type: multipart
 571         * MIME header; in that case we do not have to do the
 572         * plaintext content type even if the commit message has
 573         * non 7-bit ASCII character.  Otherwise, check if we need
 574         * to say this is not a 7-bit ASCII.
 575         */
 576        if (fmt == CMIT_FMT_EMAIL && !after_subject) {
 577                int i, ch, in_body;
 578
 579                for (in_body = i = 0; (ch = msg[i]) && i < len; i++) {
 580                        if (!in_body) {
 581                                /* author could be non 7-bit ASCII but
 582                                 * the log may so; skip over the
 583                                 * header part first.
 584                                 */
 585                                if (ch == '\n' &&
 586                                    i + 1 < len && msg[i+1] == '\n')
 587                                        in_body = 1;
 588                        }
 589                        else if (ch & 0x80) {
 590                                plain_non_ascii = 1;
 591                                break;
 592                        }
 593                }
 594        }
 595
 596        for (;;) {
 597                const char *line = msg;
 598                int linelen = get_one_line(msg, len);
 599
 600                if (!linelen)
 601                        break;
 602
 603                /*
 604                 * We want some slop for indentation and a possible
 605                 * final "...". Thus the "+ 20".
 606                 */
 607                if (offset + linelen + 20 > space) {
 608                        memcpy(buf + offset, "    ...\n", 8);
 609                        offset += 8;
 610                        break;
 611                }
 612
 613                msg += linelen;
 614                len -= linelen;
 615                if (hdr) {
 616                        if (linelen == 1) {
 617                                hdr = 0;
 618                                if ((fmt != CMIT_FMT_ONELINE) && !subject)
 619                                        buf[offset++] = '\n';
 620                                continue;
 621                        }
 622                        if (fmt == CMIT_FMT_RAW) {
 623                                memcpy(buf + offset, line, linelen);
 624                                offset += linelen;
 625                                continue;
 626                        }
 627                        if (!memcmp(line, "parent ", 7)) {
 628                                if (linelen != 48)
 629                                        die("bad parent line in commit");
 630                                continue;
 631                        }
 632
 633                        if (!parents_shown) {
 634                                offset += add_merge_info(fmt, buf + offset,
 635                                                         commit, abbrev);
 636                                parents_shown = 1;
 637                                continue;
 638                        }
 639                        /*
 640                         * MEDIUM == DEFAULT shows only author with dates.
 641                         * FULL shows both authors but not dates.
 642                         * FULLER shows both authors and dates.
 643                         */
 644                        if (!memcmp(line, "author ", 7))
 645                                offset += add_user_info("Author", fmt,
 646                                                        buf + offset,
 647                                                        line + 7);
 648                        if (!memcmp(line, "committer ", 10) &&
 649                            (fmt == CMIT_FMT_FULL || fmt == CMIT_FMT_FULLER))
 650                                offset += add_user_info("Commit", fmt,
 651                                                        buf + offset,
 652                                                        line + 10);
 653                        continue;
 654                }
 655
 656                if (is_empty_line(line, &linelen)) {
 657                        if (!body)
 658                                continue;
 659                        if (subject)
 660                                continue;
 661                        if (fmt == CMIT_FMT_SHORT)
 662                                break;
 663                } else {
 664                        body = 1;
 665                }
 666
 667                if (subject) {
 668                        int slen = strlen(subject);
 669                        memcpy(buf + offset, subject, slen);
 670                        offset += slen;
 671                        offset += add_rfc2047(buf + offset, line, linelen);
 672                }
 673                else {
 674                        memset(buf + offset, ' ', indent);
 675                        memcpy(buf + offset + indent, line, linelen);
 676                        offset += linelen + indent;
 677                }
 678                buf[offset++] = '\n';
 679                if (fmt == CMIT_FMT_ONELINE)
 680                        break;
 681                if (subject && plain_non_ascii) {
 682                        static const char header[] =
 683                                "Content-Type: text/plain; charset=UTF-8\n"
 684                                "Content-Transfer-Encoding: 8bit\n";
 685                        memcpy(buf + offset, header, sizeof(header)-1);
 686                        offset += sizeof(header)-1;
 687                }
 688                if (after_subject) {
 689                        int slen = strlen(after_subject);
 690                        if (slen > space - offset - 1)
 691                                slen = space - offset - 1;
 692                        memcpy(buf + offset, after_subject, slen);
 693                        offset += slen;
 694                        after_subject = NULL;
 695                }
 696                subject = NULL;
 697        }
 698        while (offset && isspace(buf[offset-1]))
 699                offset--;
 700        /* Make sure there is an EOLN for the non-oneline case */
 701        if (fmt != CMIT_FMT_ONELINE)
 702                buf[offset++] = '\n';
 703        buf[offset] = '\0';
 704        return offset;
 705}
 706
 707struct commit *pop_commit(struct commit_list **stack)
 708{
 709        struct commit_list *top = *stack;
 710        struct commit *item = top ? top->item : NULL;
 711
 712        if (top) {
 713                *stack = top->next;
 714                free(top);
 715        }
 716        return item;
 717}
 718
 719int count_parents(struct commit * commit)
 720{
 721        int count = 0;
 722        struct commit_list * parents = commit->parents;
 723        for (count=0;parents; parents=parents->next,count++)
 724          ;
 725        return count;
 726}
 727
 728void topo_sort_default_setter(struct commit *c, void *data)
 729{
 730        c->util = data;
 731}
 732
 733void *topo_sort_default_getter(struct commit *c)
 734{
 735        return c->util;
 736}
 737
 738/*
 739 * Performs an in-place topological sort on the list supplied.
 740 */
 741void sort_in_topological_order(struct commit_list ** list, int lifo)
 742{
 743        sort_in_topological_order_fn(list, lifo, topo_sort_default_setter,
 744                                     topo_sort_default_getter);
 745}
 746
 747void sort_in_topological_order_fn(struct commit_list ** list, int lifo,
 748                                  topo_sort_set_fn_t setter,
 749                                  topo_sort_get_fn_t getter)
 750{
 751        struct commit_list * next = *list;
 752        struct commit_list * work = NULL, **insert;
 753        struct commit_list ** pptr = list;
 754        struct sort_node * nodes;
 755        struct sort_node * next_nodes;
 756        int count = 0;
 757
 758        /* determine the size of the list */
 759        while (next) {
 760                next = next->next;
 761                count++;
 762        }
 763        
 764        if (!count)
 765                return;
 766        /* allocate an array to help sort the list */
 767        nodes = xcalloc(count, sizeof(*nodes));
 768        /* link the list to the array */
 769        next_nodes = nodes;
 770        next=*list;
 771        while (next) {
 772                next_nodes->list_item = next;
 773                setter(next->item, next_nodes);
 774                next_nodes++;
 775                next = next->next;
 776        }
 777        /* update the indegree */
 778        next=*list;
 779        while (next) {
 780                struct commit_list * parents = next->item->parents;
 781                while (parents) {
 782                        struct commit * parent=parents->item;
 783                        struct sort_node * pn = (struct sort_node *) getter(parent);
 784
 785                        if (pn)
 786                                pn->indegree++;
 787                        parents=parents->next;
 788                }
 789                next=next->next;
 790        }
 791        /* 
 792         * find the tips
 793         *
 794         * tips are nodes not reachable from any other node in the list 
 795         * 
 796         * the tips serve as a starting set for the work queue.
 797         */
 798        next=*list;
 799        insert = &work;
 800        while (next) {
 801                struct sort_node * node = (struct sort_node *) getter(next->item);
 802
 803                if (node->indegree == 0) {
 804                        insert = &commit_list_insert(next->item, insert)->next;
 805                }
 806                next=next->next;
 807        }
 808
 809        /* process the list in topological order */
 810        if (!lifo)
 811                sort_by_date(&work);
 812        while (work) {
 813                struct commit * work_item = pop_commit(&work);
 814                struct sort_node * work_node = (struct sort_node *) getter(work_item);
 815                struct commit_list * parents = work_item->parents;
 816
 817                while (parents) {
 818                        struct commit * parent=parents->item;
 819                        struct sort_node * pn = (struct sort_node *) getter(parent);
 820
 821                        if (pn) {
 822                                /*
 823                                 * parents are only enqueued for emission 
 824                                 * when all their children have been emitted thereby
 825                                 * guaranteeing topological order.
 826                                 */
 827                                pn->indegree--;
 828                                if (!pn->indegree) {
 829                                        if (!lifo)
 830                                                insert_by_date(parent, &work);
 831                                        else
 832                                                commit_list_insert(parent, &work);
 833                                }
 834                        }
 835                        parents=parents->next;
 836                }
 837                /*
 838                 * work_item is a commit all of whose children
 839                 * have already been emitted. we can emit it now.
 840                 */
 841                *pptr = work_node->list_item;
 842                pptr = &(*pptr)->next;
 843                *pptr = NULL;
 844                setter(work_item, NULL);
 845        }
 846        free(nodes);
 847}
 848
 849/* merge-rebase stuff */
 850
 851/* bits #0..7 in revision.h */
 852#define PARENT1         (1u<< 8)
 853#define PARENT2         (1u<< 9)
 854#define STALE           (1u<<10)
 855
 856static struct commit *interesting(struct commit_list *list)
 857{
 858        while (list) {
 859                struct commit *commit = list->item;
 860                list = list->next;
 861                if (commit->object.flags & STALE)
 862                        continue;
 863                return commit;
 864        }
 865        return NULL;
 866}
 867
 868/*
 869 * A pathological example of how this thing works.
 870 *
 871 * Suppose we had this commit graph, where chronologically
 872 * the timestamp on the commit are A <= B <= C <= D <= E <= F
 873 * and we are trying to figure out the merge base for E and F
 874 * commits.
 875 *
 876 *                  F
 877 *                 / \
 878 *            E   A   D
 879 *             \ /   /
 880 *              B   /
 881 *               \ /
 882 *                C
 883 *
 884 * First we push E and F to list to be processed.  E gets bit 1
 885 * and F gets bit 2.  The list becomes:
 886 *
 887 *     list=F(2) E(1), result=empty
 888 *
 889 * Then we pop F, the newest commit, from the list.  Its flag is 2.
 890 * We scan its parents, mark them reachable from the side that F is
 891 * reachable from, and push them to the list:
 892 *
 893 *     list=E(1) D(2) A(2), result=empty
 894 *
 895 * Next pop E and do the same.
 896 *
 897 *     list=D(2) B(1) A(2), result=empty
 898 *
 899 * Next pop D and do the same.
 900 *
 901 *     list=C(2) B(1) A(2), result=empty
 902 *
 903 * Next pop C and do the same.
 904 *
 905 *     list=B(1) A(2), result=empty
 906 *
 907 * Now it is B's turn.  We mark its parent, C, reachable from B's side,
 908 * and push it to the list:
 909 *
 910 *     list=C(3) A(2), result=empty
 911 *
 912 * Now pop C and notice it has flags==3.  It is placed on the result list,
 913 * and the list now contains:
 914 *
 915 *     list=A(2), result=C(3)
 916 *
 917 * We pop A and do the same.
 918 *
 919 *     list=B(3), result=C(3)
 920 *
 921 * Next, we pop B and something very interesting happens.  It has flags==3
 922 * so it is also placed on the result list, and its parents are marked
 923 * stale, retroactively, and placed back on the list:
 924 *
 925 *    list=C(7), result=C(7) B(3)
 926 *
 927 * Now, list does not have any interesting commit.  So we find the newest
 928 * commit from the result list that is not marked stale.  Which is
 929 * commit B.
 930 *
 931 *
 932 * Another pathological example how this thing used to fail to mark an
 933 * ancestor of a merge base as STALE before we introduced the
 934 * postprocessing phase (mark_reachable_commits).
 935 *
 936 *                2
 937 *                H
 938 *          1    / \
 939 *          G   A   \
 940 *          |\ /     \
 941 *          | B       \
 942 *          |  \       \
 943 *           \  C       F
 944 *            \  \     /
 945 *             \  D   /
 946 *              \ |  /
 947 *               \| /
 948 *                E
 949 *
 950 *       list                   A B C D E F G H
 951 *       G1 H2                  - - - - - - 1 2
 952 *       H2 E1 B1               - 1 - - 1 - 1 2
 953 *       F2 E1 B1 A2            2 1 - - 1 2 1 2
 954 *       E3 B1 A2               2 1 - - 3 2 1 2
 955 *       B1 A2                  2 1 - - 3 2 1 2
 956 *       C1 A2                  2 1 1 - 3 2 1 2
 957 *       D1 A2                  2 1 1 1 3 2 1 2
 958 *       A2                     2 1 1 1 3 2 1 2
 959 *       B3                     2 3 1 1 3 2 1 2
 960 *       C7                     2 3 7 1 3 2 1 2
 961 *
 962 * At this point, unfortunately, everybody in the list is
 963 * stale, so we fail to complete the following two
 964 * steps to fully marking stale commits.
 965 *
 966 *       D7                     2 3 7 7 3 2 1 2
 967 *       E7                     2 3 7 7 7 2 1 2
 968 *
 969 * and we ended up showing E as an interesting merge base.
 970 * The postprocessing phase re-injects C and continues traversal
 971 * to contaminate D and E.
 972 */
 973
 974static void mark_reachable_commits(struct commit_list *result,
 975                                   struct commit_list *list)
 976{
 977        struct commit_list *tmp;
 978
 979        /*
 980         * Postprocess to fully contaminate the well.
 981         */
 982        for (tmp = result; tmp; tmp = tmp->next) {
 983                struct commit *c = tmp->item;
 984                /* Reinject stale ones to list,
 985                 * so we can scan their parents.
 986                 */
 987                if (c->object.flags & STALE)
 988                        commit_list_insert(c, &list);
 989        }
 990        while (list) {
 991                struct commit *c = list->item;
 992                struct commit_list *parents;
 993
 994                tmp = list;
 995                list = list->next;
 996                free(tmp);
 997
 998                /* Anything taken out of the list is stale, so
 999                 * mark all its parents stale.  We do not
1000                 * parse new ones (we already parsed all the relevant
1001                 * ones).
1002                 */
1003                parents = c->parents;
1004                while (parents) {
1005                        struct commit *p = parents->item;
1006                        parents = parents->next;
1007                        if (!(p->object.flags & STALE)) {
1008                                p->object.flags |= STALE;
1009                                commit_list_insert(p, &list);
1010                        }
1011                }
1012        }
1013}
1014
1015struct commit_list *get_merge_bases(struct commit *rev1, struct commit *rev2,
1016                                    int cleanup)
1017{
1018        struct commit_list *list = NULL;
1019        struct commit_list *result = NULL;
1020        struct commit_list *tmp = NULL;
1021
1022        if (rev1 == rev2)
1023                return commit_list_insert(rev1, &result);
1024
1025        parse_commit(rev1);
1026        parse_commit(rev2);
1027
1028        rev1->object.flags |= PARENT1;
1029        rev2->object.flags |= PARENT2;
1030        insert_by_date(rev1, &list);
1031        insert_by_date(rev2, &list);
1032
1033        while (interesting(list)) {
1034                struct commit *commit = list->item;
1035                struct commit_list *parents;
1036                int flags = commit->object.flags
1037                        & (PARENT1 | PARENT2 | STALE);
1038
1039                tmp = list;
1040                list = list->next;
1041                free(tmp);
1042                if (flags == (PARENT1 | PARENT2)) {
1043                        insert_by_date(commit, &result);
1044
1045                        /* Mark parents of a found merge stale */
1046                        flags |= STALE;
1047                }
1048                parents = commit->parents;
1049                while (parents) {
1050                        struct commit *p = parents->item;
1051                        parents = parents->next;
1052                        if ((p->object.flags & flags) == flags)
1053                                continue;
1054                        parse_commit(p);
1055                        p->object.flags |= flags;
1056                        insert_by_date(p, &list);
1057                }
1058        }
1059
1060        if (!result)
1061                return NULL;
1062
1063        if (result->next && list)
1064                mark_reachable_commits(result, list);
1065
1066        /* cull duplicates */
1067        for (tmp = result, list = NULL; tmp; ) {
1068                struct commit *commit = tmp->item;
1069                struct commit_list *next = tmp->next;
1070                if (commit->object.flags & STALE) {
1071                        if (list != NULL)
1072                                list->next = next;
1073                        free(tmp);
1074                } else {
1075                        if (list == NULL)
1076                                result = tmp;
1077                        list = tmp;
1078                        commit->object.flags |= STALE;
1079                }
1080
1081                tmp = next;
1082        }
1083
1084        if (cleanup) {
1085                clear_commit_marks(rev1, PARENT1 | PARENT2 | STALE);
1086                clear_commit_marks(rev2, PARENT1 | PARENT2 | STALE);
1087        }
1088
1089        return result;
1090}