91be0ce0a059c39c6949fff7f9e50d89d9330685
   1#include "cache.h"
   2#include "commit.h"
   3#include "utf8.h"
   4#include "diff.h"
   5#include "revision.h"
   6#include "string-list.h"
   7#include "mailmap.h"
   8#include "log-tree.h"
   9#include "color.h"
  10
  11static char *user_format;
  12
  13static void save_user_format(struct rev_info *rev, const char *cp, int is_tformat)
  14{
  15        free(user_format);
  16        user_format = xstrdup(cp);
  17        if (is_tformat)
  18                rev->use_terminator = 1;
  19        rev->commit_format = CMIT_FMT_USERFORMAT;
  20}
  21
  22void get_commit_format(const char *arg, struct rev_info *rev)
  23{
  24        int i;
  25        static struct 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
  39        rev->use_terminator = 0;
  40        if (!arg || !*arg) {
  41                rev->commit_format = CMIT_FMT_DEFAULT;
  42                return;
  43        }
  44        if (!prefixcmp(arg, "format:") || !prefixcmp(arg, "tformat:")) {
  45                save_user_format(rev, strchr(arg, ':') + 1, arg[0] == 't');
  46                return;
  47        }
  48        for (i = 0; i < ARRAY_SIZE(cmt_fmts); i++) {
  49                if (!strncmp(arg, cmt_fmts[i].n, cmt_fmts[i].cmp_len) &&
  50                    !strncmp(arg, cmt_fmts[i].n, strlen(arg))) {
  51                        if (cmt_fmts[i].v == CMIT_FMT_ONELINE)
  52                                rev->use_terminator = 1;
  53                        rev->commit_format = cmt_fmts[i].v;
  54                        return;
  55                }
  56        }
  57        if (strchr(arg, '%')) {
  58                save_user_format(rev, arg, 1);
  59                return;
  60        }
  61
  62        die("invalid --pretty format: %s", arg);
  63}
  64
  65/*
  66 * Generic support for pretty-printing the header
  67 */
  68static int get_one_line(const char *msg)
  69{
  70        int ret = 0;
  71
  72        for (;;) {
  73                char c = *msg++;
  74                if (!c)
  75                        break;
  76                ret++;
  77                if (c == '\n')
  78                        break;
  79        }
  80        return ret;
  81}
  82
  83/* High bit set, or ISO-2022-INT */
  84int non_ascii(int ch)
  85{
  86        return !isascii(ch) || ch == '\033';
  87}
  88
  89int has_non_ascii(const char *s)
  90{
  91        int ch;
  92        if (!s)
  93                return 0;
  94        while ((ch = *s++) != '\0') {
  95                if (non_ascii(ch))
  96                        return 1;
  97        }
  98        return 0;
  99}
 100
 101static int is_rfc2047_special(char ch)
 102{
 103        return (non_ascii(ch) || (ch == '=') || (ch == '?') || (ch == '_'));
 104}
 105
 106static void add_rfc2047(struct strbuf *sb, const char *line, int len,
 107                       const char *encoding)
 108{
 109        int i, last;
 110
 111        for (i = 0; i < len; i++) {
 112                int ch = line[i];
 113                if (non_ascii(ch))
 114                        goto needquote;
 115                if ((i + 1 < len) && (ch == '=' && line[i+1] == '?'))
 116                        goto needquote;
 117        }
 118        strbuf_add(sb, line, len);
 119        return;
 120
 121needquote:
 122        strbuf_grow(sb, len * 3 + strlen(encoding) + 100);
 123        strbuf_addf(sb, "=?%s?q?", encoding);
 124        for (i = last = 0; i < len; i++) {
 125                unsigned ch = line[i] & 0xFF;
 126                /*
 127                 * We encode ' ' using '=20' even though rfc2047
 128                 * allows using '_' for readability.  Unfortunately,
 129                 * many programs do not understand this and just
 130                 * leave the underscore in place.
 131                 */
 132                if (is_rfc2047_special(ch) || ch == ' ') {
 133                        strbuf_add(sb, line + last, i - last);
 134                        strbuf_addf(sb, "=%02X", ch);
 135                        last = i + 1;
 136                }
 137        }
 138        strbuf_add(sb, line + last, len - last);
 139        strbuf_addstr(sb, "?=");
 140}
 141
 142void pp_user_info(const char *what, enum cmit_fmt fmt, struct strbuf *sb,
 143                  const char *line, enum date_mode dmode,
 144                  const char *encoding)
 145{
 146        char *date;
 147        int namelen;
 148        unsigned long time;
 149        int tz;
 150
 151        if (fmt == CMIT_FMT_ONELINE)
 152                return;
 153        date = strchr(line, '>');
 154        if (!date)
 155                return;
 156        namelen = ++date - line;
 157        time = strtoul(date, &date, 10);
 158        tz = strtol(date, NULL, 10);
 159
 160        if (fmt == CMIT_FMT_EMAIL) {
 161                char *name_tail = strchr(line, '<');
 162                int display_name_length;
 163                if (!name_tail)
 164                        return;
 165                while (line < name_tail && isspace(name_tail[-1]))
 166                        name_tail--;
 167                display_name_length = name_tail - line;
 168                strbuf_addstr(sb, "From: ");
 169                add_rfc2047(sb, line, display_name_length, encoding);
 170                strbuf_add(sb, name_tail, namelen - display_name_length);
 171                strbuf_addch(sb, '\n');
 172        } else {
 173                strbuf_addf(sb, "%s: %.*s%.*s\n", what,
 174                              (fmt == CMIT_FMT_FULLER) ? 4 : 0,
 175                              "    ", namelen, line);
 176        }
 177        switch (fmt) {
 178        case CMIT_FMT_MEDIUM:
 179                strbuf_addf(sb, "Date:   %s\n", show_date(time, tz, dmode));
 180                break;
 181        case CMIT_FMT_EMAIL:
 182                strbuf_addf(sb, "Date: %s\n", show_date(time, tz, DATE_RFC2822));
 183                break;
 184        case CMIT_FMT_FULLER:
 185                strbuf_addf(sb, "%sDate: %s\n", what, show_date(time, tz, dmode));
 186                break;
 187        default:
 188                /* notin' */
 189                break;
 190        }
 191}
 192
 193static int is_empty_line(const char *line, int *len_p)
 194{
 195        int len = *len_p;
 196        while (len && isspace(line[len-1]))
 197                len--;
 198        *len_p = len;
 199        return !len;
 200}
 201
 202static const char *skip_empty_lines(const char *msg)
 203{
 204        for (;;) {
 205                int linelen = get_one_line(msg);
 206                int ll = linelen;
 207                if (!linelen)
 208                        break;
 209                if (!is_empty_line(msg, &ll))
 210                        break;
 211                msg += linelen;
 212        }
 213        return msg;
 214}
 215
 216static void add_merge_info(enum cmit_fmt fmt, struct strbuf *sb,
 217                        const struct commit *commit, int abbrev)
 218{
 219        struct commit_list *parent = commit->parents;
 220
 221        if ((fmt == CMIT_FMT_ONELINE) || (fmt == CMIT_FMT_EMAIL) ||
 222            !parent || !parent->next)
 223                return;
 224
 225        strbuf_addstr(sb, "Merge:");
 226
 227        while (parent) {
 228                struct commit *p = parent->item;
 229                const char *hex = NULL;
 230                if (abbrev)
 231                        hex = find_unique_abbrev(p->object.sha1, abbrev);
 232                if (!hex)
 233                        hex = sha1_to_hex(p->object.sha1);
 234                parent = parent->next;
 235
 236                strbuf_addf(sb, " %s", hex);
 237        }
 238        strbuf_addch(sb, '\n');
 239}
 240
 241static char *get_header(const struct commit *commit, const char *key)
 242{
 243        int key_len = strlen(key);
 244        const char *line = commit->buffer;
 245
 246        for (;;) {
 247                const char *eol = strchr(line, '\n'), *next;
 248
 249                if (line == eol)
 250                        return NULL;
 251                if (!eol) {
 252                        eol = line + strlen(line);
 253                        next = NULL;
 254                } else
 255                        next = eol + 1;
 256                if (eol - line > key_len &&
 257                    !strncmp(line, key, key_len) &&
 258                    line[key_len] == ' ') {
 259                        return xmemdupz(line + key_len + 1, eol - line - key_len - 1);
 260                }
 261                line = next;
 262        }
 263}
 264
 265static char *replace_encoding_header(char *buf, const char *encoding)
 266{
 267        struct strbuf tmp = STRBUF_INIT;
 268        size_t start, len;
 269        char *cp = buf;
 270
 271        /* guess if there is an encoding header before a \n\n */
 272        while (strncmp(cp, "encoding ", strlen("encoding "))) {
 273                cp = strchr(cp, '\n');
 274                if (!cp || *++cp == '\n')
 275                        return buf;
 276        }
 277        start = cp - buf;
 278        cp = strchr(cp, '\n');
 279        if (!cp)
 280                return buf; /* should not happen but be defensive */
 281        len = cp + 1 - (buf + start);
 282
 283        strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
 284        if (is_encoding_utf8(encoding)) {
 285                /* we have re-coded to UTF-8; drop the header */
 286                strbuf_remove(&tmp, start, len);
 287        } else {
 288                /* just replaces XXXX in 'encoding XXXX\n' */
 289                strbuf_splice(&tmp, start + strlen("encoding "),
 290                                          len - strlen("encoding \n"),
 291                                          encoding, strlen(encoding));
 292        }
 293        return strbuf_detach(&tmp, NULL);
 294}
 295
 296static char *logmsg_reencode(const struct commit *commit,
 297                             const char *output_encoding)
 298{
 299        static const char *utf8 = "UTF-8";
 300        const char *use_encoding;
 301        char *encoding;
 302        char *out;
 303
 304        if (!*output_encoding)
 305                return NULL;
 306        encoding = get_header(commit, "encoding");
 307        use_encoding = encoding ? encoding : utf8;
 308        if (!strcmp(use_encoding, output_encoding))
 309                if (encoding) /* we'll strip encoding header later */
 310                        out = xstrdup(commit->buffer);
 311                else
 312                        return NULL; /* nothing to do */
 313        else
 314                out = reencode_string(commit->buffer,
 315                                      output_encoding, use_encoding);
 316        if (out)
 317                out = replace_encoding_header(out, output_encoding);
 318
 319        free(encoding);
 320        return out;
 321}
 322
 323static int mailmap_name(char *email, int email_len, char *name, int name_len)
 324{
 325        static struct string_list *mail_map;
 326        if (!mail_map) {
 327                mail_map = xcalloc(1, sizeof(*mail_map));
 328                read_mailmap(mail_map, NULL);
 329        }
 330        return mail_map->nr && map_user(mail_map, email, email_len, name, name_len);
 331}
 332
 333static size_t format_person_part(struct strbuf *sb, char part,
 334                                 const char *msg, int len, enum date_mode dmode)
 335{
 336        /* currently all placeholders have same length */
 337        const int placeholder_len = 2;
 338        int start, end, tz = 0;
 339        unsigned long date = 0;
 340        char *ep;
 341        const char *name_start, *name_end, *mail_start, *mail_end, *msg_end = msg+len;
 342        char person_name[1024];
 343        char person_mail[1024];
 344
 345        /* advance 'end' to point to email start delimiter */
 346        for (end = 0; end < len && msg[end] != '<'; end++)
 347                ; /* do nothing */
 348
 349        /*
 350         * When end points at the '<' that we found, it should have
 351         * matching '>' later, which means 'end' must be strictly
 352         * below len - 1.
 353         */
 354        if (end >= len - 2)
 355                goto skip;
 356
 357        /* Seek for both name and email part */
 358        name_start = msg;
 359        name_end = msg+end;
 360        while (name_end > name_start && isspace(*(name_end-1)))
 361                name_end--;
 362        mail_start = msg+end+1;
 363        mail_end = mail_start;
 364        while (mail_end < msg_end && *mail_end != '>')
 365                mail_end++;
 366        if (mail_end == msg_end)
 367                goto skip;
 368        end = mail_end-msg;
 369
 370        if (part == 'N' || part == 'E') { /* mailmap lookup */
 371                strlcpy(person_name, name_start, name_end-name_start+1);
 372                strlcpy(person_mail, mail_start, mail_end-mail_start+1);
 373                mailmap_name(person_mail, sizeof(person_mail), person_name, sizeof(person_name));
 374                name_start = person_name;
 375                name_end = name_start + strlen(person_name);
 376                mail_start = person_mail;
 377                mail_end = mail_start +  strlen(person_mail);
 378        }
 379        if (part == 'n' || part == 'N') {       /* name */
 380                strbuf_add(sb, name_start, name_end-name_start);
 381                return placeholder_len;
 382        }
 383        if (part == 'e' || part == 'E') {       /* email */
 384                strbuf_add(sb, mail_start, mail_end-mail_start);
 385                return placeholder_len;
 386        }
 387
 388        /* advance 'start' to point to date start delimiter */
 389        for (start = end + 1; start < len && isspace(msg[start]); start++)
 390                ; /* do nothing */
 391        if (start >= len)
 392                goto skip;
 393        date = strtoul(msg + start, &ep, 10);
 394        if (msg + start == ep)
 395                goto skip;
 396
 397        if (part == 't') {      /* date, UNIX timestamp */
 398                strbuf_add(sb, msg + start, ep - (msg + start));
 399                return placeholder_len;
 400        }
 401
 402        /* parse tz */
 403        for (start = ep - msg + 1; start < len && isspace(msg[start]); start++)
 404                ; /* do nothing */
 405        if (start + 1 < len) {
 406                tz = strtoul(msg + start + 1, NULL, 10);
 407                if (msg[start] == '-')
 408                        tz = -tz;
 409        }
 410
 411        switch (part) {
 412        case 'd':       /* date */
 413                strbuf_addstr(sb, show_date(date, tz, dmode));
 414                return placeholder_len;
 415        case 'D':       /* date, RFC2822 style */
 416                strbuf_addstr(sb, show_date(date, tz, DATE_RFC2822));
 417                return placeholder_len;
 418        case 'r':       /* date, relative */
 419                strbuf_addstr(sb, show_date(date, tz, DATE_RELATIVE));
 420                return placeholder_len;
 421        case 'i':       /* date, ISO 8601 */
 422                strbuf_addstr(sb, show_date(date, tz, DATE_ISO8601));
 423                return placeholder_len;
 424        }
 425
 426skip:
 427        /*
 428         * bogus commit, 'sb' cannot be updated, but we still need to
 429         * compute a valid return value.
 430         */
 431        if (part == 'n' || part == 'e' || part == 't' || part == 'd'
 432            || part == 'D' || part == 'r' || part == 'i')
 433                return placeholder_len;
 434
 435        return 0; /* unknown placeholder */
 436}
 437
 438struct chunk {
 439        size_t off;
 440        size_t len;
 441};
 442
 443struct format_commit_context {
 444        const struct commit *commit;
 445        enum date_mode dmode;
 446        unsigned commit_header_parsed:1;
 447        unsigned commit_message_parsed:1;
 448        size_t width, indent1, indent2;
 449
 450        /* These offsets are relative to the start of the commit message. */
 451        struct chunk author;
 452        struct chunk committer;
 453        struct chunk encoding;
 454        size_t message_off;
 455        size_t subject_off;
 456        size_t body_off;
 457
 458        /* The following ones are relative to the result struct strbuf. */
 459        struct chunk abbrev_commit_hash;
 460        struct chunk abbrev_tree_hash;
 461        struct chunk abbrev_parent_hashes;
 462        size_t wrap_start;
 463};
 464
 465static int add_again(struct strbuf *sb, struct chunk *chunk)
 466{
 467        if (chunk->len) {
 468                strbuf_adddup(sb, chunk->off, chunk->len);
 469                return 1;
 470        }
 471
 472        /*
 473         * We haven't seen this chunk before.  Our caller is surely
 474         * going to add it the hard way now.  Remember the most likely
 475         * start of the to-be-added chunk: the current end of the
 476         * struct strbuf.
 477         */
 478        chunk->off = sb->len;
 479        return 0;
 480}
 481
 482static void parse_commit_header(struct format_commit_context *context)
 483{
 484        const char *msg = context->commit->buffer;
 485        int i;
 486
 487        for (i = 0; msg[i]; i++) {
 488                int eol;
 489                for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
 490                        ; /* do nothing */
 491
 492                if (i == eol) {
 493                        break;
 494                } else if (!prefixcmp(msg + i, "author ")) {
 495                        context->author.off = i + 7;
 496                        context->author.len = eol - i - 7;
 497                } else if (!prefixcmp(msg + i, "committer ")) {
 498                        context->committer.off = i + 10;
 499                        context->committer.len = eol - i - 10;
 500                } else if (!prefixcmp(msg + i, "encoding ")) {
 501                        context->encoding.off = i + 9;
 502                        context->encoding.len = eol - i - 9;
 503                }
 504                i = eol;
 505        }
 506        context->message_off = i;
 507        context->commit_header_parsed = 1;
 508}
 509
 510static int istitlechar(char c)
 511{
 512        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
 513                (c >= '0' && c <= '9') || c == '.' || c == '_';
 514}
 515
 516static void format_sanitized_subject(struct strbuf *sb, const char *msg)
 517{
 518        size_t trimlen;
 519        size_t start_len = sb->len;
 520        int space = 2;
 521
 522        for (; *msg && *msg != '\n'; msg++) {
 523                if (istitlechar(*msg)) {
 524                        if (space == 1)
 525                                strbuf_addch(sb, '-');
 526                        space = 0;
 527                        strbuf_addch(sb, *msg);
 528                        if (*msg == '.')
 529                                while (*(msg+1) == '.')
 530                                        msg++;
 531                } else
 532                        space |= 1;
 533        }
 534
 535        /* trim any trailing '.' or '-' characters */
 536        trimlen = 0;
 537        while (sb->len - trimlen > start_len &&
 538                (sb->buf[sb->len - 1 - trimlen] == '.'
 539                || sb->buf[sb->len - 1 - trimlen] == '-'))
 540                trimlen++;
 541        strbuf_remove(sb, sb->len - trimlen, trimlen);
 542}
 543
 544const char *format_subject(struct strbuf *sb, const char *msg,
 545                           const char *line_separator)
 546{
 547        int first = 1;
 548
 549        for (;;) {
 550                const char *line = msg;
 551                int linelen = get_one_line(line);
 552
 553                msg += linelen;
 554                if (!linelen || is_empty_line(line, &linelen))
 555                        break;
 556
 557                if (!sb)
 558                        continue;
 559                strbuf_grow(sb, linelen + 2);
 560                if (!first)
 561                        strbuf_addstr(sb, line_separator);
 562                strbuf_add(sb, line, linelen);
 563                first = 0;
 564        }
 565        return msg;
 566}
 567
 568static void parse_commit_message(struct format_commit_context *c)
 569{
 570        const char *msg = c->commit->buffer + c->message_off;
 571        const char *start = c->commit->buffer;
 572
 573        msg = skip_empty_lines(msg);
 574        c->subject_off = msg - start;
 575
 576        msg = format_subject(NULL, msg, NULL);
 577        msg = skip_empty_lines(msg);
 578        c->body_off = msg - start;
 579
 580        c->commit_message_parsed = 1;
 581}
 582
 583static void format_decoration(struct strbuf *sb, const struct commit *commit)
 584{
 585        struct name_decoration *d;
 586        const char *prefix = " (";
 587
 588        load_ref_decorations(DECORATE_SHORT_REFS);
 589        d = lookup_decoration(&name_decoration, &commit->object);
 590        while (d) {
 591                strbuf_addstr(sb, prefix);
 592                prefix = ", ";
 593                strbuf_addstr(sb, d->name);
 594                d = d->next;
 595        }
 596        if (prefix[0] == ',')
 597                strbuf_addch(sb, ')');
 598}
 599
 600static void strbuf_wrap(struct strbuf *sb, size_t pos,
 601                        size_t width, size_t indent1, size_t indent2)
 602{
 603        struct strbuf tmp = STRBUF_INIT;
 604
 605        if (pos)
 606                strbuf_add(&tmp, sb->buf, pos);
 607        strbuf_add_wrapped_text(&tmp, sb->buf + pos,
 608                                (int) indent1, (int) indent2, (int) width);
 609        strbuf_swap(&tmp, sb);
 610        strbuf_release(&tmp);
 611}
 612
 613static void rewrap_message_tail(struct strbuf *sb,
 614                                struct format_commit_context *c,
 615                                size_t new_width, size_t new_indent1,
 616                                size_t new_indent2)
 617{
 618        if (c->width == new_width && c->indent1 == new_indent1 &&
 619            c->indent2 == new_indent2)
 620                return;
 621        if (c->wrap_start && c->wrap_start < sb->len)
 622                strbuf_wrap(sb, c->wrap_start, c->width, c->indent1, c->indent2);
 623        c->wrap_start = sb->len;
 624        c->width = new_width;
 625        c->indent1 = new_indent1;
 626        c->indent2 = new_indent2;
 627}
 628
 629static size_t format_commit_item(struct strbuf *sb, const char *placeholder,
 630                               void *context)
 631{
 632        struct format_commit_context *c = context;
 633        const struct commit *commit = c->commit;
 634        const char *msg = commit->buffer;
 635        struct commit_list *p;
 636        int h1, h2;
 637
 638        /* these are independent of the commit */
 639        switch (placeholder[0]) {
 640        case 'C':
 641                if (placeholder[1] == '(') {
 642                        const char *end = strchr(placeholder + 2, ')');
 643                        char color[COLOR_MAXLEN];
 644                        if (!end)
 645                                return 0;
 646                        color_parse_mem(placeholder + 2,
 647                                        end - (placeholder + 2),
 648                                        "--pretty format", color);
 649                        strbuf_addstr(sb, color);
 650                        return end - placeholder + 1;
 651                }
 652                if (!prefixcmp(placeholder + 1, "red")) {
 653                        strbuf_addstr(sb, GIT_COLOR_RED);
 654                        return 4;
 655                } else if (!prefixcmp(placeholder + 1, "green")) {
 656                        strbuf_addstr(sb, GIT_COLOR_GREEN);
 657                        return 6;
 658                } else if (!prefixcmp(placeholder + 1, "blue")) {
 659                        strbuf_addstr(sb, GIT_COLOR_BLUE);
 660                        return 5;
 661                } else if (!prefixcmp(placeholder + 1, "reset")) {
 662                        strbuf_addstr(sb, GIT_COLOR_RESET);
 663                        return 6;
 664                } else
 665                        return 0;
 666        case 'n':               /* newline */
 667                strbuf_addch(sb, '\n');
 668                return 1;
 669        case 'x':
 670                /* %x00 == NUL, %x0a == LF, etc. */
 671                if (0 <= (h1 = hexval_table[0xff & placeholder[1]]) &&
 672                    h1 <= 16 &&
 673                    0 <= (h2 = hexval_table[0xff & placeholder[2]]) &&
 674                    h2 <= 16) {
 675                        strbuf_addch(sb, (h1<<4)|h2);
 676                        return 3;
 677                } else
 678                        return 0;
 679        case 'w':
 680                if (placeholder[1] == '(') {
 681                        unsigned long width = 0, indent1 = 0, indent2 = 0;
 682                        char *next;
 683                        const char *start = placeholder + 2;
 684                        const char *end = strchr(start, ')');
 685                        if (!end)
 686                                return 0;
 687                        if (end > start) {
 688                                width = strtoul(start, &next, 10);
 689                                if (*next == ',') {
 690                                        indent1 = strtoul(next + 1, &next, 10);
 691                                        if (*next == ',') {
 692                                                indent2 = strtoul(next + 1,
 693                                                                 &next, 10);
 694                                        }
 695                                }
 696                                if (*next != ')')
 697                                        return 0;
 698                        }
 699                        rewrap_message_tail(sb, c, width, indent1, indent2);
 700                        return end - placeholder + 1;
 701                } else
 702                        return 0;
 703        }
 704
 705        /* these depend on the commit */
 706        if (!commit->object.parsed)
 707                parse_object(commit->object.sha1);
 708
 709        switch (placeholder[0]) {
 710        case 'H':               /* commit hash */
 711                strbuf_addstr(sb, sha1_to_hex(commit->object.sha1));
 712                return 1;
 713        case 'h':               /* abbreviated commit hash */
 714                if (add_again(sb, &c->abbrev_commit_hash))
 715                        return 1;
 716                strbuf_addstr(sb, find_unique_abbrev(commit->object.sha1,
 717                                                     DEFAULT_ABBREV));
 718                c->abbrev_commit_hash.len = sb->len - c->abbrev_commit_hash.off;
 719                return 1;
 720        case 'T':               /* tree hash */
 721                strbuf_addstr(sb, sha1_to_hex(commit->tree->object.sha1));
 722                return 1;
 723        case 't':               /* abbreviated tree hash */
 724                if (add_again(sb, &c->abbrev_tree_hash))
 725                        return 1;
 726                strbuf_addstr(sb, find_unique_abbrev(commit->tree->object.sha1,
 727                                                     DEFAULT_ABBREV));
 728                c->abbrev_tree_hash.len = sb->len - c->abbrev_tree_hash.off;
 729                return 1;
 730        case 'P':               /* parent hashes */
 731                for (p = commit->parents; p; p = p->next) {
 732                        if (p != commit->parents)
 733                                strbuf_addch(sb, ' ');
 734                        strbuf_addstr(sb, sha1_to_hex(p->item->object.sha1));
 735                }
 736                return 1;
 737        case 'p':               /* abbreviated parent hashes */
 738                if (add_again(sb, &c->abbrev_parent_hashes))
 739                        return 1;
 740                for (p = commit->parents; p; p = p->next) {
 741                        if (p != commit->parents)
 742                                strbuf_addch(sb, ' ');
 743                        strbuf_addstr(sb, find_unique_abbrev(
 744                                        p->item->object.sha1, DEFAULT_ABBREV));
 745                }
 746                c->abbrev_parent_hashes.len = sb->len -
 747                                              c->abbrev_parent_hashes.off;
 748                return 1;
 749        case 'm':               /* left/right/bottom */
 750                strbuf_addch(sb, (commit->object.flags & BOUNDARY)
 751                                 ? '-'
 752                                 : (commit->object.flags & SYMMETRIC_LEFT)
 753                                 ? '<'
 754                                 : '>');
 755                return 1;
 756        case 'd':
 757                format_decoration(sb, commit);
 758                return 1;
 759        }
 760
 761        /* For the rest we have to parse the commit header. */
 762        if (!c->commit_header_parsed)
 763                parse_commit_header(c);
 764
 765        switch (placeholder[0]) {
 766        case 'a':       /* author ... */
 767                return format_person_part(sb, placeholder[1],
 768                                   msg + c->author.off, c->author.len,
 769                                   c->dmode);
 770        case 'c':       /* committer ... */
 771                return format_person_part(sb, placeholder[1],
 772                                   msg + c->committer.off, c->committer.len,
 773                                   c->dmode);
 774        case 'e':       /* encoding */
 775                strbuf_add(sb, msg + c->encoding.off, c->encoding.len);
 776                return 1;
 777        }
 778
 779        /* Now we need to parse the commit message. */
 780        if (!c->commit_message_parsed)
 781                parse_commit_message(c);
 782
 783        switch (placeholder[0]) {
 784        case 's':       /* subject */
 785                format_subject(sb, msg + c->subject_off, " ");
 786                return 1;
 787        case 'f':       /* sanitized subject */
 788                format_sanitized_subject(sb, msg + c->subject_off);
 789                return 1;
 790        case 'b':       /* body */
 791                strbuf_addstr(sb, msg + c->body_off);
 792                return 1;
 793        }
 794        return 0;       /* unknown placeholder */
 795}
 796
 797void format_commit_message(const struct commit *commit,
 798                           const char *format, struct strbuf *sb,
 799                           enum date_mode dmode)
 800{
 801        struct format_commit_context context;
 802
 803        memset(&context, 0, sizeof(context));
 804        context.commit = commit;
 805        context.dmode = dmode;
 806        context.wrap_start = sb->len;
 807        strbuf_expand(sb, format, format_commit_item, &context);
 808        rewrap_message_tail(sb, &context, 0, 0, 0);
 809}
 810
 811static void pp_header(enum cmit_fmt fmt,
 812                      int abbrev,
 813                      enum date_mode dmode,
 814                      const char *encoding,
 815                      const struct commit *commit,
 816                      const char **msg_p,
 817                      struct strbuf *sb)
 818{
 819        int parents_shown = 0;
 820
 821        for (;;) {
 822                const char *line = *msg_p;
 823                int linelen = get_one_line(*msg_p);
 824
 825                if (!linelen)
 826                        return;
 827                *msg_p += linelen;
 828
 829                if (linelen == 1)
 830                        /* End of header */
 831                        return;
 832
 833                if (fmt == CMIT_FMT_RAW) {
 834                        strbuf_add(sb, line, linelen);
 835                        continue;
 836                }
 837
 838                if (!memcmp(line, "parent ", 7)) {
 839                        if (linelen != 48)
 840                                die("bad parent line in commit");
 841                        continue;
 842                }
 843
 844                if (!parents_shown) {
 845                        struct commit_list *parent;
 846                        int num;
 847                        for (parent = commit->parents, num = 0;
 848                             parent;
 849                             parent = parent->next, num++)
 850                                ;
 851                        /* with enough slop */
 852                        strbuf_grow(sb, num * 50 + 20);
 853                        add_merge_info(fmt, sb, commit, abbrev);
 854                        parents_shown = 1;
 855                }
 856
 857                /*
 858                 * MEDIUM == DEFAULT shows only author with dates.
 859                 * FULL shows both authors but not dates.
 860                 * FULLER shows both authors and dates.
 861                 */
 862                if (!memcmp(line, "author ", 7)) {
 863                        strbuf_grow(sb, linelen + 80);
 864                        pp_user_info("Author", fmt, sb, line + 7, dmode, encoding);
 865                }
 866                if (!memcmp(line, "committer ", 10) &&
 867                    (fmt == CMIT_FMT_FULL || fmt == CMIT_FMT_FULLER)) {
 868                        strbuf_grow(sb, linelen + 80);
 869                        pp_user_info("Commit", fmt, sb, line + 10, dmode, encoding);
 870                }
 871        }
 872}
 873
 874void pp_title_line(enum cmit_fmt fmt,
 875                   const char **msg_p,
 876                   struct strbuf *sb,
 877                   const char *subject,
 878                   const char *after_subject,
 879                   const char *encoding,
 880                   int need_8bit_cte)
 881{
 882        const char *line_separator = (fmt == CMIT_FMT_EMAIL) ? "\n " : " ";
 883        struct strbuf title;
 884
 885        strbuf_init(&title, 80);
 886        *msg_p = format_subject(&title, *msg_p, line_separator);
 887
 888        strbuf_grow(sb, title.len + 1024);
 889        if (subject) {
 890                strbuf_addstr(sb, subject);
 891                add_rfc2047(sb, title.buf, title.len, encoding);
 892        } else {
 893                strbuf_addbuf(sb, &title);
 894        }
 895        strbuf_addch(sb, '\n');
 896
 897        if (need_8bit_cte > 0) {
 898                const char *header_fmt =
 899                        "MIME-Version: 1.0\n"
 900                        "Content-Type: text/plain; charset=%s\n"
 901                        "Content-Transfer-Encoding: 8bit\n";
 902                strbuf_addf(sb, header_fmt, encoding);
 903        }
 904        if (after_subject) {
 905                strbuf_addstr(sb, after_subject);
 906        }
 907        if (fmt == CMIT_FMT_EMAIL) {
 908                strbuf_addch(sb, '\n');
 909        }
 910        strbuf_release(&title);
 911}
 912
 913void pp_remainder(enum cmit_fmt fmt,
 914                  const char **msg_p,
 915                  struct strbuf *sb,
 916                  int indent)
 917{
 918        int first = 1;
 919        for (;;) {
 920                const char *line = *msg_p;
 921                int linelen = get_one_line(line);
 922                *msg_p += linelen;
 923
 924                if (!linelen)
 925                        break;
 926
 927                if (is_empty_line(line, &linelen)) {
 928                        if (first)
 929                                continue;
 930                        if (fmt == CMIT_FMT_SHORT)
 931                                break;
 932                }
 933                first = 0;
 934
 935                strbuf_grow(sb, linelen + indent + 20);
 936                if (indent) {
 937                        memset(sb->buf + sb->len, ' ', indent);
 938                        strbuf_setlen(sb, sb->len + indent);
 939                }
 940                strbuf_add(sb, line, linelen);
 941                strbuf_addch(sb, '\n');
 942        }
 943}
 944
 945char *reencode_commit_message(const struct commit *commit, const char **encoding_p)
 946{
 947        const char *encoding;
 948
 949        encoding = (git_log_output_encoding
 950                    ? git_log_output_encoding
 951                    : git_commit_encoding);
 952        if (!encoding)
 953                encoding = "UTF-8";
 954        if (encoding_p)
 955                *encoding_p = encoding;
 956        return logmsg_reencode(commit, encoding);
 957}
 958
 959void pretty_print_commit(enum cmit_fmt fmt, const struct commit *commit,
 960                         struct strbuf *sb, int abbrev,
 961                         const char *subject, const char *after_subject,
 962                         enum date_mode dmode, int need_8bit_cte)
 963{
 964        unsigned long beginning_of_body;
 965        int indent = 4;
 966        const char *msg = commit->buffer;
 967        char *reencoded;
 968        const char *encoding;
 969
 970        if (fmt == CMIT_FMT_USERFORMAT) {
 971                format_commit_message(commit, user_format, sb, dmode);
 972                return;
 973        }
 974
 975        reencoded = reencode_commit_message(commit, &encoding);
 976        if (reencoded) {
 977                msg = reencoded;
 978        }
 979
 980        if (fmt == CMIT_FMT_ONELINE || fmt == CMIT_FMT_EMAIL)
 981                indent = 0;
 982
 983        /*
 984         * We need to check and emit Content-type: to mark it
 985         * as 8-bit if we haven't done so.
 986         */
 987        if (fmt == CMIT_FMT_EMAIL && need_8bit_cte == 0) {
 988                int i, ch, in_body;
 989
 990                for (in_body = i = 0; (ch = msg[i]); i++) {
 991                        if (!in_body) {
 992                                /* author could be non 7-bit ASCII but
 993                                 * the log may be so; skip over the
 994                                 * header part first.
 995                                 */
 996                                if (ch == '\n' && msg[i+1] == '\n')
 997                                        in_body = 1;
 998                        }
 999                        else if (non_ascii(ch)) {
1000                                need_8bit_cte = 1;
1001                                break;
1002                        }
1003                }
1004        }
1005
1006        pp_header(fmt, abbrev, dmode, encoding, commit, &msg, sb);
1007        if (fmt != CMIT_FMT_ONELINE && !subject) {
1008                strbuf_addch(sb, '\n');
1009        }
1010
1011        /* Skip excess blank lines at the beginning of body, if any... */
1012        msg = skip_empty_lines(msg);
1013
1014        /* These formats treat the title line specially. */
1015        if (fmt == CMIT_FMT_ONELINE || fmt == CMIT_FMT_EMAIL)
1016                pp_title_line(fmt, &msg, sb, subject,
1017                              after_subject, encoding, need_8bit_cte);
1018
1019        beginning_of_body = sb->len;
1020        if (fmt != CMIT_FMT_ONELINE)
1021                pp_remainder(fmt, &msg, sb, indent);
1022        strbuf_rtrim(sb);
1023
1024        /* Make sure there is an EOLN for the non-oneline case */
1025        if (fmt != CMIT_FMT_ONELINE)
1026                strbuf_addch(sb, '\n');
1027
1028        /*
1029         * The caller may append additional body text in e-mail
1030         * format.  Make sure we did not strip the blank line
1031         * between the header and the body.
1032         */
1033        if (fmt == CMIT_FMT_EMAIL && sb->len <= beginning_of_body)
1034                strbuf_addch(sb, '\n');
1035        free(reencoded);
1036}