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