pretty.con commit format-patch: RFC 2047 says multi-octet character may not be split (6cd3c05)
   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 "notes.h"
  10#include "color.h"
  11#include "reflog-walk.h"
  12#include "gpg-interface.h"
  13
  14static char *user_format;
  15static struct cmt_fmt_map {
  16        const char *name;
  17        enum cmit_fmt format;
  18        int is_tformat;
  19        int is_alias;
  20        const char *user_format;
  21} *commit_formats;
  22static size_t builtin_formats_len;
  23static size_t commit_formats_len;
  24static size_t commit_formats_alloc;
  25static struct cmt_fmt_map *find_commit_format(const char *sought);
  26
  27static void save_user_format(struct rev_info *rev, const char *cp, int is_tformat)
  28{
  29        free(user_format);
  30        user_format = xstrdup(cp);
  31        if (is_tformat)
  32                rev->use_terminator = 1;
  33        rev->commit_format = CMIT_FMT_USERFORMAT;
  34}
  35
  36static int git_pretty_formats_config(const char *var, const char *value, void *cb)
  37{
  38        struct cmt_fmt_map *commit_format = NULL;
  39        const char *name;
  40        const char *fmt;
  41        int i;
  42
  43        if (prefixcmp(var, "pretty."))
  44                return 0;
  45
  46        name = var + strlen("pretty.");
  47        for (i = 0; i < builtin_formats_len; i++) {
  48                if (!strcmp(commit_formats[i].name, name))
  49                        return 0;
  50        }
  51
  52        for (i = builtin_formats_len; i < commit_formats_len; i++) {
  53                if (!strcmp(commit_formats[i].name, name)) {
  54                        commit_format = &commit_formats[i];
  55                        break;
  56                }
  57        }
  58
  59        if (!commit_format) {
  60                ALLOC_GROW(commit_formats, commit_formats_len+1,
  61                           commit_formats_alloc);
  62                commit_format = &commit_formats[commit_formats_len];
  63                memset(commit_format, 0, sizeof(*commit_format));
  64                commit_formats_len++;
  65        }
  66
  67        commit_format->name = xstrdup(name);
  68        commit_format->format = CMIT_FMT_USERFORMAT;
  69        git_config_string(&fmt, var, value);
  70        if (!prefixcmp(fmt, "format:") || !prefixcmp(fmt, "tformat:")) {
  71                commit_format->is_tformat = fmt[0] == 't';
  72                fmt = strchr(fmt, ':') + 1;
  73        } else if (strchr(fmt, '%'))
  74                commit_format->is_tformat = 1;
  75        else
  76                commit_format->is_alias = 1;
  77        commit_format->user_format = fmt;
  78
  79        return 0;
  80}
  81
  82static void setup_commit_formats(void)
  83{
  84        struct cmt_fmt_map builtin_formats[] = {
  85                { "raw",        CMIT_FMT_RAW,           0 },
  86                { "medium",     CMIT_FMT_MEDIUM,        0 },
  87                { "short",      CMIT_FMT_SHORT,         0 },
  88                { "email",      CMIT_FMT_EMAIL,         0 },
  89                { "fuller",     CMIT_FMT_FULLER,        0 },
  90                { "full",       CMIT_FMT_FULL,          0 },
  91                { "oneline",    CMIT_FMT_ONELINE,       1 }
  92        };
  93        commit_formats_len = ARRAY_SIZE(builtin_formats);
  94        builtin_formats_len = commit_formats_len;
  95        ALLOC_GROW(commit_formats, commit_formats_len, commit_formats_alloc);
  96        memcpy(commit_formats, builtin_formats,
  97               sizeof(*builtin_formats)*ARRAY_SIZE(builtin_formats));
  98
  99        git_config(git_pretty_formats_config, NULL);
 100}
 101
 102static struct cmt_fmt_map *find_commit_format_recursive(const char *sought,
 103                                                        const char *original,
 104                                                        int num_redirections)
 105{
 106        struct cmt_fmt_map *found = NULL;
 107        size_t found_match_len = 0;
 108        int i;
 109
 110        if (num_redirections >= commit_formats_len)
 111                die("invalid --pretty format: "
 112                    "'%s' references an alias which points to itself",
 113                    original);
 114
 115        for (i = 0; i < commit_formats_len; i++) {
 116                size_t match_len;
 117
 118                if (prefixcmp(commit_formats[i].name, sought))
 119                        continue;
 120
 121                match_len = strlen(commit_formats[i].name);
 122                if (found == NULL || found_match_len > match_len) {
 123                        found = &commit_formats[i];
 124                        found_match_len = match_len;
 125                }
 126        }
 127
 128        if (found && found->is_alias) {
 129                found = find_commit_format_recursive(found->user_format,
 130                                                     original,
 131                                                     num_redirections+1);
 132        }
 133
 134        return found;
 135}
 136
 137static struct cmt_fmt_map *find_commit_format(const char *sought)
 138{
 139        if (!commit_formats)
 140                setup_commit_formats();
 141
 142        return find_commit_format_recursive(sought, sought, 0);
 143}
 144
 145void get_commit_format(const char *arg, struct rev_info *rev)
 146{
 147        struct cmt_fmt_map *commit_format;
 148
 149        rev->use_terminator = 0;
 150        if (!arg || !*arg) {
 151                rev->commit_format = CMIT_FMT_DEFAULT;
 152                return;
 153        }
 154        if (!prefixcmp(arg, "format:") || !prefixcmp(arg, "tformat:")) {
 155                save_user_format(rev, strchr(arg, ':') + 1, arg[0] == 't');
 156                return;
 157        }
 158
 159        if (strchr(arg, '%')) {
 160                save_user_format(rev, arg, 1);
 161                return;
 162        }
 163
 164        commit_format = find_commit_format(arg);
 165        if (!commit_format)
 166                die("invalid --pretty format: %s", arg);
 167
 168        rev->commit_format = commit_format->format;
 169        rev->use_terminator = commit_format->is_tformat;
 170        if (commit_format->format == CMIT_FMT_USERFORMAT) {
 171                save_user_format(rev, commit_format->user_format,
 172                                 commit_format->is_tformat);
 173        }
 174}
 175
 176/*
 177 * Generic support for pretty-printing the header
 178 */
 179static int get_one_line(const char *msg)
 180{
 181        int ret = 0;
 182
 183        for (;;) {
 184                char c = *msg++;
 185                if (!c)
 186                        break;
 187                ret++;
 188                if (c == '\n')
 189                        break;
 190        }
 191        return ret;
 192}
 193
 194/* High bit set, or ISO-2022-INT */
 195static int non_ascii(int ch)
 196{
 197        return !isascii(ch) || ch == '\033';
 198}
 199
 200int has_non_ascii(const char *s)
 201{
 202        int ch;
 203        if (!s)
 204                return 0;
 205        while ((ch = *s++) != '\0') {
 206                if (non_ascii(ch))
 207                        return 1;
 208        }
 209        return 0;
 210}
 211
 212static int is_rfc822_special(char ch)
 213{
 214        switch (ch) {
 215        case '(':
 216        case ')':
 217        case '<':
 218        case '>':
 219        case '[':
 220        case ']':
 221        case ':':
 222        case ';':
 223        case '@':
 224        case ',':
 225        case '.':
 226        case '"':
 227        case '\\':
 228                return 1;
 229        default:
 230                return 0;
 231        }
 232}
 233
 234static int needs_rfc822_quoting(const char *s, int len)
 235{
 236        int i;
 237        for (i = 0; i < len; i++)
 238                if (is_rfc822_special(s[i]))
 239                        return 1;
 240        return 0;
 241}
 242
 243static int last_line_length(struct strbuf *sb)
 244{
 245        int i;
 246
 247        /* How many bytes are already used on the last line? */
 248        for (i = sb->len - 1; i >= 0; i--)
 249                if (sb->buf[i] == '\n')
 250                        break;
 251        return sb->len - (i + 1);
 252}
 253
 254static void add_rfc822_quoted(struct strbuf *out, const char *s, int len)
 255{
 256        int i;
 257
 258        /* just a guess, we may have to also backslash-quote */
 259        strbuf_grow(out, len + 2);
 260
 261        strbuf_addch(out, '"');
 262        for (i = 0; i < len; i++) {
 263                switch (s[i]) {
 264                case '"':
 265                case '\\':
 266                        strbuf_addch(out, '\\');
 267                        /* fall through */
 268                default:
 269                        strbuf_addch(out, s[i]);
 270                }
 271        }
 272        strbuf_addch(out, '"');
 273}
 274
 275enum rfc2047_type {
 276        RFC2047_SUBJECT,
 277        RFC2047_ADDRESS,
 278};
 279
 280static int is_rfc2047_special(char ch, enum rfc2047_type type)
 281{
 282        /*
 283         * rfc2047, section 4.2:
 284         *
 285         *    8-bit values which correspond to printable ASCII characters other
 286         *    than "=", "?", and "_" (underscore), MAY be represented as those
 287         *    characters.  (But see section 5 for restrictions.)  In
 288         *    particular, SPACE and TAB MUST NOT be represented as themselves
 289         *    within encoded words.
 290         */
 291
 292        /*
 293         * rule out non-ASCII characters and non-printable characters (the
 294         * non-ASCII check should be redundant as isprint() is not localized
 295         * and only knows about ASCII, but be defensive about that)
 296         */
 297        if (non_ascii(ch) || !isprint(ch))
 298                return 1;
 299
 300        /*
 301         * rule out special printable characters (' ' should be the only
 302         * whitespace character considered printable, but be defensive and use
 303         * isspace())
 304         */
 305        if (isspace(ch) || ch == '=' || ch == '?' || ch == '_')
 306                return 1;
 307
 308        /*
 309         * rfc2047, section 5.3:
 310         *
 311         *    As a replacement for a 'word' entity within a 'phrase', for example,
 312         *    one that precedes an address in a From, To, or Cc header.  The ABNF
 313         *    definition for 'phrase' from RFC 822 thus becomes:
 314         *
 315         *    phrase = 1*( encoded-word / word )
 316         *
 317         *    In this case the set of characters that may be used in a "Q"-encoded
 318         *    'encoded-word' is restricted to: <upper and lower case ASCII
 319         *    letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
 320         *    (underscore, ASCII 95.)>.  An 'encoded-word' that appears within a
 321         *    'phrase' MUST be separated from any adjacent 'word', 'text' or
 322         *    'special' by 'linear-white-space'.
 323         */
 324
 325        if (type != RFC2047_ADDRESS)
 326                return 0;
 327
 328        /* '=' and '_' are special cases and have been checked above */
 329        return !(isalnum(ch) || ch == '!' || ch == '*' || ch == '+' || ch == '-' || ch == '/');
 330}
 331
 332static int needs_rfc2047_encoding(const char *line, int len,
 333                                  enum rfc2047_type type)
 334{
 335        int i;
 336
 337        for (i = 0; i < len; i++) {
 338                int ch = line[i];
 339                if (non_ascii(ch) || ch == '\n')
 340                        return 1;
 341                if ((i + 1 < len) && (ch == '=' && line[i+1] == '?'))
 342                        return 1;
 343        }
 344
 345        return 0;
 346}
 347
 348static void add_rfc2047(struct strbuf *sb, const char *line, size_t len,
 349                       const char *encoding, enum rfc2047_type type)
 350{
 351        static const int max_encoded_length = 76; /* per rfc2047 */
 352        int i;
 353        int line_len = last_line_length(sb);
 354
 355        strbuf_grow(sb, len * 3 + strlen(encoding) + 100);
 356        strbuf_addf(sb, "=?%s?q?", encoding);
 357        line_len += strlen(encoding) + 5; /* 5 for =??q? */
 358
 359        while (len) {
 360                /*
 361                 * RFC 2047, section 5 (3):
 362                 *
 363                 * Each 'encoded-word' MUST represent an integral number of
 364                 * characters.  A multi-octet character may not be split across
 365                 * adjacent 'encoded- word's.
 366                 */
 367                const unsigned char *p = (const unsigned char *)line;
 368                int chrlen = mbs_chrlen(&line, &len, encoding);
 369                int is_special = (chrlen > 1) || is_rfc2047_special(*p, type);
 370
 371                /* "=%02X" * chrlen, or the byte itself */
 372                const char *encoded_fmt = is_special ? "=%02X"    : "%c";
 373                int         encoded_len = is_special ? 3 * chrlen : 1;
 374
 375                /*
 376                 * According to RFC 2047, we could encode the special character
 377                 * ' ' (space) with '_' (underscore) for readability. But many
 378                 * programs do not understand this and just leave the
 379                 * underscore in place. Thus, we do nothing special here, which
 380                 * causes ' ' to be encoded as '=20', avoiding this problem.
 381                 */
 382
 383                if (line_len + encoded_len + 2 > max_encoded_length) {
 384                        /* It won't fit with trailing "?=" --- break the line */
 385                        strbuf_addf(sb, "?=\n =?%s?q?", encoding);
 386                        line_len = strlen(encoding) + 5 + 1; /* =??q? plus SP */
 387                }
 388
 389                for (i = 0; i < chrlen; i++)
 390                        strbuf_addf(sb, encoded_fmt, p[i]);
 391                line_len += encoded_len;
 392        }
 393        strbuf_addstr(sb, "?=");
 394}
 395
 396void pp_user_info(const struct pretty_print_context *pp,
 397                  const char *what, struct strbuf *sb,
 398                  const char *line, const char *encoding)
 399{
 400        int max_length = 78; /* per rfc2822 */
 401        char *date;
 402        int namelen;
 403        unsigned long time;
 404        int tz;
 405
 406        if (pp->fmt == CMIT_FMT_ONELINE)
 407                return;
 408        date = strchr(line, '>');
 409        if (!date)
 410                return;
 411        namelen = ++date - line;
 412        time = strtoul(date, &date, 10);
 413        tz = strtol(date, NULL, 10);
 414
 415        if (pp->fmt == CMIT_FMT_EMAIL) {
 416                char *name_tail = strchr(line, '<');
 417                int display_name_length;
 418                if (!name_tail)
 419                        return;
 420                while (line < name_tail && isspace(name_tail[-1]))
 421                        name_tail--;
 422                display_name_length = name_tail - line;
 423                strbuf_addstr(sb, "From: ");
 424                if (needs_rfc2047_encoding(line, display_name_length, RFC2047_ADDRESS)) {
 425                        add_rfc2047(sb, line, display_name_length,
 426                                                encoding, RFC2047_ADDRESS);
 427                        max_length = 76; /* per rfc2047 */
 428                } else if (needs_rfc822_quoting(line, display_name_length)) {
 429                        struct strbuf quoted = STRBUF_INIT;
 430                        add_rfc822_quoted(&quoted, line, display_name_length);
 431                        strbuf_add_wrapped_bytes(sb, quoted.buf, quoted.len,
 432                                                        -6, 1, max_length);
 433                        strbuf_release(&quoted);
 434                } else {
 435                        strbuf_add_wrapped_bytes(sb, line, display_name_length,
 436                                                        -6, 1, max_length);
 437                }
 438                if (namelen - display_name_length + last_line_length(sb) > max_length) {
 439                        strbuf_addch(sb, '\n');
 440                        if (!isspace(name_tail[0]))
 441                                strbuf_addch(sb, ' ');
 442                }
 443                strbuf_add(sb, name_tail, namelen - display_name_length);
 444                strbuf_addch(sb, '\n');
 445        } else {
 446                strbuf_addf(sb, "%s: %.*s%.*s\n", what,
 447                              (pp->fmt == CMIT_FMT_FULLER) ? 4 : 0,
 448                              "    ", namelen, line);
 449        }
 450        switch (pp->fmt) {
 451        case CMIT_FMT_MEDIUM:
 452                strbuf_addf(sb, "Date:   %s\n", show_date(time, tz, pp->date_mode));
 453                break;
 454        case CMIT_FMT_EMAIL:
 455                strbuf_addf(sb, "Date: %s\n", show_date(time, tz, DATE_RFC2822));
 456                break;
 457        case CMIT_FMT_FULLER:
 458                strbuf_addf(sb, "%sDate: %s\n", what, show_date(time, tz, pp->date_mode));
 459                break;
 460        default:
 461                /* notin' */
 462                break;
 463        }
 464}
 465
 466static int is_empty_line(const char *line, int *len_p)
 467{
 468        int len = *len_p;
 469        while (len && isspace(line[len-1]))
 470                len--;
 471        *len_p = len;
 472        return !len;
 473}
 474
 475static const char *skip_empty_lines(const char *msg)
 476{
 477        for (;;) {
 478                int linelen = get_one_line(msg);
 479                int ll = linelen;
 480                if (!linelen)
 481                        break;
 482                if (!is_empty_line(msg, &ll))
 483                        break;
 484                msg += linelen;
 485        }
 486        return msg;
 487}
 488
 489static void add_merge_info(const struct pretty_print_context *pp,
 490                           struct strbuf *sb, const struct commit *commit)
 491{
 492        struct commit_list *parent = commit->parents;
 493
 494        if ((pp->fmt == CMIT_FMT_ONELINE) || (pp->fmt == CMIT_FMT_EMAIL) ||
 495            !parent || !parent->next)
 496                return;
 497
 498        strbuf_addstr(sb, "Merge:");
 499
 500        while (parent) {
 501                struct commit *p = parent->item;
 502                const char *hex = NULL;
 503                if (pp->abbrev)
 504                        hex = find_unique_abbrev(p->object.sha1, pp->abbrev);
 505                if (!hex)
 506                        hex = sha1_to_hex(p->object.sha1);
 507                parent = parent->next;
 508
 509                strbuf_addf(sb, " %s", hex);
 510        }
 511        strbuf_addch(sb, '\n');
 512}
 513
 514static char *get_header(const struct commit *commit, const char *key)
 515{
 516        int key_len = strlen(key);
 517        const char *line = commit->buffer;
 518
 519        while (line) {
 520                const char *eol = strchr(line, '\n'), *next;
 521
 522                if (line == eol)
 523                        return NULL;
 524                if (!eol) {
 525                        warning("malformed commit (header is missing newline): %s",
 526                                sha1_to_hex(commit->object.sha1));
 527                        eol = line + strlen(line);
 528                        next = NULL;
 529                } else
 530                        next = eol + 1;
 531                if (eol - line > key_len &&
 532                    !strncmp(line, key, key_len) &&
 533                    line[key_len] == ' ') {
 534                        return xmemdupz(line + key_len + 1, eol - line - key_len - 1);
 535                }
 536                line = next;
 537        }
 538        return NULL;
 539}
 540
 541static char *replace_encoding_header(char *buf, const char *encoding)
 542{
 543        struct strbuf tmp = STRBUF_INIT;
 544        size_t start, len;
 545        char *cp = buf;
 546
 547        /* guess if there is an encoding header before a \n\n */
 548        while (strncmp(cp, "encoding ", strlen("encoding "))) {
 549                cp = strchr(cp, '\n');
 550                if (!cp || *++cp == '\n')
 551                        return buf;
 552        }
 553        start = cp - buf;
 554        cp = strchr(cp, '\n');
 555        if (!cp)
 556                return buf; /* should not happen but be defensive */
 557        len = cp + 1 - (buf + start);
 558
 559        strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
 560        if (is_encoding_utf8(encoding)) {
 561                /* we have re-coded to UTF-8; drop the header */
 562                strbuf_remove(&tmp, start, len);
 563        } else {
 564                /* just replaces XXXX in 'encoding XXXX\n' */
 565                strbuf_splice(&tmp, start + strlen("encoding "),
 566                                          len - strlen("encoding \n"),
 567                                          encoding, strlen(encoding));
 568        }
 569        return strbuf_detach(&tmp, NULL);
 570}
 571
 572char *logmsg_reencode(const struct commit *commit,
 573                      const char *output_encoding)
 574{
 575        static const char *utf8 = "UTF-8";
 576        const char *use_encoding;
 577        char *encoding;
 578        char *out;
 579
 580        if (!*output_encoding)
 581                return NULL;
 582        encoding = get_header(commit, "encoding");
 583        use_encoding = encoding ? encoding : utf8;
 584        if (same_encoding(use_encoding, output_encoding))
 585                if (encoding) /* we'll strip encoding header later */
 586                        out = xstrdup(commit->buffer);
 587                else
 588                        return NULL; /* nothing to do */
 589        else
 590                out = reencode_string(commit->buffer,
 591                                      output_encoding, use_encoding);
 592        if (out)
 593                out = replace_encoding_header(out, output_encoding);
 594
 595        free(encoding);
 596        return out;
 597}
 598
 599static int mailmap_name(char *email, int email_len, char *name, int name_len)
 600{
 601        static struct string_list *mail_map;
 602        if (!mail_map) {
 603                mail_map = xcalloc(1, sizeof(*mail_map));
 604                read_mailmap(mail_map, NULL);
 605        }
 606        return mail_map->nr && map_user(mail_map, email, email_len, name, name_len);
 607}
 608
 609static size_t format_person_part(struct strbuf *sb, char part,
 610                                 const char *msg, int len, enum date_mode dmode)
 611{
 612        /* currently all placeholders have same length */
 613        const int placeholder_len = 2;
 614        int tz;
 615        unsigned long date = 0;
 616        char person_name[1024];
 617        char person_mail[1024];
 618        struct ident_split s;
 619        const char *name_start, *name_end, *mail_start, *mail_end;
 620
 621        if (split_ident_line(&s, msg, len) < 0)
 622                goto skip;
 623
 624        name_start = s.name_begin;
 625        name_end = s.name_end;
 626        mail_start = s.mail_begin;
 627        mail_end = s.mail_end;
 628
 629        if (part == 'N' || part == 'E') { /* mailmap lookup */
 630                snprintf(person_name, sizeof(person_name), "%.*s",
 631                         (int)(name_end - name_start), name_start);
 632                snprintf(person_mail, sizeof(person_mail), "%.*s",
 633                         (int)(mail_end - mail_start), mail_start);
 634                mailmap_name(person_mail, sizeof(person_mail), person_name, sizeof(person_name));
 635                name_start = person_name;
 636                name_end = name_start + strlen(person_name);
 637                mail_start = person_mail;
 638                mail_end = mail_start +  strlen(person_mail);
 639        }
 640        if (part == 'n' || part == 'N') {       /* name */
 641                strbuf_add(sb, name_start, name_end-name_start);
 642                return placeholder_len;
 643        }
 644        if (part == 'e' || part == 'E') {       /* email */
 645                strbuf_add(sb, mail_start, mail_end-mail_start);
 646                return placeholder_len;
 647        }
 648
 649        if (!s.date_begin)
 650                goto skip;
 651
 652        date = strtoul(s.date_begin, NULL, 10);
 653
 654        if (part == 't') {      /* date, UNIX timestamp */
 655                strbuf_add(sb, s.date_begin, s.date_end - s.date_begin);
 656                return placeholder_len;
 657        }
 658
 659        /* parse tz */
 660        tz = strtoul(s.tz_begin + 1, NULL, 10);
 661        if (*s.tz_begin == '-')
 662                tz = -tz;
 663
 664        switch (part) {
 665        case 'd':       /* date */
 666                strbuf_addstr(sb, show_date(date, tz, dmode));
 667                return placeholder_len;
 668        case 'D':       /* date, RFC2822 style */
 669                strbuf_addstr(sb, show_date(date, tz, DATE_RFC2822));
 670                return placeholder_len;
 671        case 'r':       /* date, relative */
 672                strbuf_addstr(sb, show_date(date, tz, DATE_RELATIVE));
 673                return placeholder_len;
 674        case 'i':       /* date, ISO 8601 */
 675                strbuf_addstr(sb, show_date(date, tz, DATE_ISO8601));
 676                return placeholder_len;
 677        }
 678
 679skip:
 680        /*
 681         * reading from either a bogus commit, or a reflog entry with
 682         * %gn, %ge, etc.; 'sb' cannot be updated, but we still need
 683         * to compute a valid return value.
 684         */
 685        if (part == 'n' || part == 'e' || part == 't' || part == 'd'
 686            || part == 'D' || part == 'r' || part == 'i')
 687                return placeholder_len;
 688
 689        return 0; /* unknown placeholder */
 690}
 691
 692struct chunk {
 693        size_t off;
 694        size_t len;
 695};
 696
 697struct format_commit_context {
 698        const struct commit *commit;
 699        const struct pretty_print_context *pretty_ctx;
 700        unsigned commit_header_parsed:1;
 701        unsigned commit_message_parsed:1;
 702        unsigned commit_signature_parsed:1;
 703        struct {
 704                char *gpg_output;
 705                char good_bad;
 706                char *signer;
 707        } signature;
 708        char *message;
 709        size_t width, indent1, indent2;
 710
 711        /* These offsets are relative to the start of the commit message. */
 712        struct chunk author;
 713        struct chunk committer;
 714        struct chunk encoding;
 715        size_t message_off;
 716        size_t subject_off;
 717        size_t body_off;
 718
 719        /* The following ones are relative to the result struct strbuf. */
 720        struct chunk abbrev_commit_hash;
 721        struct chunk abbrev_tree_hash;
 722        struct chunk abbrev_parent_hashes;
 723        size_t wrap_start;
 724};
 725
 726static int add_again(struct strbuf *sb, struct chunk *chunk)
 727{
 728        if (chunk->len) {
 729                strbuf_adddup(sb, chunk->off, chunk->len);
 730                return 1;
 731        }
 732
 733        /*
 734         * We haven't seen this chunk before.  Our caller is surely
 735         * going to add it the hard way now.  Remember the most likely
 736         * start of the to-be-added chunk: the current end of the
 737         * struct strbuf.
 738         */
 739        chunk->off = sb->len;
 740        return 0;
 741}
 742
 743static void parse_commit_header(struct format_commit_context *context)
 744{
 745        const char *msg = context->message;
 746        int i;
 747
 748        for (i = 0; msg[i]; i++) {
 749                int eol;
 750                for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
 751                        ; /* do nothing */
 752
 753                if (i == eol) {
 754                        break;
 755                } else if (!prefixcmp(msg + i, "author ")) {
 756                        context->author.off = i + 7;
 757                        context->author.len = eol - i - 7;
 758                } else if (!prefixcmp(msg + i, "committer ")) {
 759                        context->committer.off = i + 10;
 760                        context->committer.len = eol - i - 10;
 761                } else if (!prefixcmp(msg + i, "encoding ")) {
 762                        context->encoding.off = i + 9;
 763                        context->encoding.len = eol - i - 9;
 764                }
 765                i = eol;
 766        }
 767        context->message_off = i;
 768        context->commit_header_parsed = 1;
 769}
 770
 771static int istitlechar(char c)
 772{
 773        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
 774                (c >= '0' && c <= '9') || c == '.' || c == '_';
 775}
 776
 777static void format_sanitized_subject(struct strbuf *sb, const char *msg)
 778{
 779        size_t trimlen;
 780        size_t start_len = sb->len;
 781        int space = 2;
 782
 783        for (; *msg && *msg != '\n'; msg++) {
 784                if (istitlechar(*msg)) {
 785                        if (space == 1)
 786                                strbuf_addch(sb, '-');
 787                        space = 0;
 788                        strbuf_addch(sb, *msg);
 789                        if (*msg == '.')
 790                                while (*(msg+1) == '.')
 791                                        msg++;
 792                } else
 793                        space |= 1;
 794        }
 795
 796        /* trim any trailing '.' or '-' characters */
 797        trimlen = 0;
 798        while (sb->len - trimlen > start_len &&
 799                (sb->buf[sb->len - 1 - trimlen] == '.'
 800                || sb->buf[sb->len - 1 - trimlen] == '-'))
 801                trimlen++;
 802        strbuf_remove(sb, sb->len - trimlen, trimlen);
 803}
 804
 805const char *format_subject(struct strbuf *sb, const char *msg,
 806                           const char *line_separator)
 807{
 808        int first = 1;
 809
 810        for (;;) {
 811                const char *line = msg;
 812                int linelen = get_one_line(line);
 813
 814                msg += linelen;
 815                if (!linelen || is_empty_line(line, &linelen))
 816                        break;
 817
 818                if (!sb)
 819                        continue;
 820                strbuf_grow(sb, linelen + 2);
 821                if (!first)
 822                        strbuf_addstr(sb, line_separator);
 823                strbuf_add(sb, line, linelen);
 824                first = 0;
 825        }
 826        return msg;
 827}
 828
 829static void parse_commit_message(struct format_commit_context *c)
 830{
 831        const char *msg = c->message + c->message_off;
 832        const char *start = c->message;
 833
 834        msg = skip_empty_lines(msg);
 835        c->subject_off = msg - start;
 836
 837        msg = format_subject(NULL, msg, NULL);
 838        msg = skip_empty_lines(msg);
 839        c->body_off = msg - start;
 840
 841        c->commit_message_parsed = 1;
 842}
 843
 844static void format_decoration(struct strbuf *sb, const struct commit *commit)
 845{
 846        struct name_decoration *d;
 847        const char *prefix = " (";
 848
 849        load_ref_decorations(DECORATE_SHORT_REFS);
 850        d = lookup_decoration(&name_decoration, &commit->object);
 851        while (d) {
 852                strbuf_addstr(sb, prefix);
 853                prefix = ", ";
 854                strbuf_addstr(sb, d->name);
 855                d = d->next;
 856        }
 857        if (prefix[0] == ',')
 858                strbuf_addch(sb, ')');
 859}
 860
 861static void strbuf_wrap(struct strbuf *sb, size_t pos,
 862                        size_t width, size_t indent1, size_t indent2)
 863{
 864        struct strbuf tmp = STRBUF_INIT;
 865
 866        if (pos)
 867                strbuf_add(&tmp, sb->buf, pos);
 868        strbuf_add_wrapped_text(&tmp, sb->buf + pos,
 869                                (int) indent1, (int) indent2, (int) width);
 870        strbuf_swap(&tmp, sb);
 871        strbuf_release(&tmp);
 872}
 873
 874static void rewrap_message_tail(struct strbuf *sb,
 875                                struct format_commit_context *c,
 876                                size_t new_width, size_t new_indent1,
 877                                size_t new_indent2)
 878{
 879        if (c->width == new_width && c->indent1 == new_indent1 &&
 880            c->indent2 == new_indent2)
 881                return;
 882        if (c->wrap_start < sb->len)
 883                strbuf_wrap(sb, c->wrap_start, c->width, c->indent1, c->indent2);
 884        c->wrap_start = sb->len;
 885        c->width = new_width;
 886        c->indent1 = new_indent1;
 887        c->indent2 = new_indent2;
 888}
 889
 890static struct {
 891        char result;
 892        const char *check;
 893} signature_check[] = {
 894        { 'G', ": Good signature from " },
 895        { 'B', ": BAD signature from " },
 896};
 897
 898static void parse_signature_lines(struct format_commit_context *ctx)
 899{
 900        const char *buf = ctx->signature.gpg_output;
 901        int i;
 902
 903        for (i = 0; i < ARRAY_SIZE(signature_check); i++) {
 904                const char *found = strstr(buf, signature_check[i].check);
 905                const char *next;
 906                if (!found)
 907                        continue;
 908                ctx->signature.good_bad = signature_check[i].result;
 909                found += strlen(signature_check[i].check);
 910                next = strchrnul(found, '\n');
 911                ctx->signature.signer = xmemdupz(found, next - found);
 912                break;
 913        }
 914}
 915
 916static void parse_commit_signature(struct format_commit_context *ctx)
 917{
 918        struct strbuf payload = STRBUF_INIT;
 919        struct strbuf signature = STRBUF_INIT;
 920        struct strbuf gpg_output = STRBUF_INIT;
 921        int status;
 922
 923        ctx->commit_signature_parsed = 1;
 924
 925        if (parse_signed_commit(ctx->commit->object.sha1,
 926                                &payload, &signature) <= 0)
 927                goto out;
 928        status = verify_signed_buffer(payload.buf, payload.len,
 929                                      signature.buf, signature.len,
 930                                      &gpg_output);
 931        if (status && !gpg_output.len)
 932                goto out;
 933        ctx->signature.gpg_output = strbuf_detach(&gpg_output, NULL);
 934        parse_signature_lines(ctx);
 935
 936 out:
 937        strbuf_release(&gpg_output);
 938        strbuf_release(&payload);
 939        strbuf_release(&signature);
 940}
 941
 942
 943static int format_reflog_person(struct strbuf *sb,
 944                                char part,
 945                                struct reflog_walk_info *log,
 946                                enum date_mode dmode)
 947{
 948        const char *ident;
 949
 950        if (!log)
 951                return 2;
 952
 953        ident = get_reflog_ident(log);
 954        if (!ident)
 955                return 2;
 956
 957        return format_person_part(sb, part, ident, strlen(ident), dmode);
 958}
 959
 960static size_t format_commit_one(struct strbuf *sb, const char *placeholder,
 961                                void *context)
 962{
 963        struct format_commit_context *c = context;
 964        const struct commit *commit = c->commit;
 965        const char *msg = c->message;
 966        struct commit_list *p;
 967        int h1, h2;
 968
 969        /* these are independent of the commit */
 970        switch (placeholder[0]) {
 971        case 'C':
 972                if (placeholder[1] == '(') {
 973                        const char *end = strchr(placeholder + 2, ')');
 974                        char color[COLOR_MAXLEN];
 975                        if (!end)
 976                                return 0;
 977                        color_parse_mem(placeholder + 2,
 978                                        end - (placeholder + 2),
 979                                        "--pretty format", color);
 980                        strbuf_addstr(sb, color);
 981                        return end - placeholder + 1;
 982                }
 983                if (!prefixcmp(placeholder + 1, "red")) {
 984                        strbuf_addstr(sb, GIT_COLOR_RED);
 985                        return 4;
 986                } else if (!prefixcmp(placeholder + 1, "green")) {
 987                        strbuf_addstr(sb, GIT_COLOR_GREEN);
 988                        return 6;
 989                } else if (!prefixcmp(placeholder + 1, "blue")) {
 990                        strbuf_addstr(sb, GIT_COLOR_BLUE);
 991                        return 5;
 992                } else if (!prefixcmp(placeholder + 1, "reset")) {
 993                        strbuf_addstr(sb, GIT_COLOR_RESET);
 994                        return 6;
 995                } else
 996                        return 0;
 997        case 'n':               /* newline */
 998                strbuf_addch(sb, '\n');
 999                return 1;
1000        case 'x':
1001                /* %x00 == NUL, %x0a == LF, etc. */
1002                if (0 <= (h1 = hexval_table[0xff & placeholder[1]]) &&
1003                    h1 <= 16 &&
1004                    0 <= (h2 = hexval_table[0xff & placeholder[2]]) &&
1005                    h2 <= 16) {
1006                        strbuf_addch(sb, (h1<<4)|h2);
1007                        return 3;
1008                } else
1009                        return 0;
1010        case 'w':
1011                if (placeholder[1] == '(') {
1012                        unsigned long width = 0, indent1 = 0, indent2 = 0;
1013                        char *next;
1014                        const char *start = placeholder + 2;
1015                        const char *end = strchr(start, ')');
1016                        if (!end)
1017                                return 0;
1018                        if (end > start) {
1019                                width = strtoul(start, &next, 10);
1020                                if (*next == ',') {
1021                                        indent1 = strtoul(next + 1, &next, 10);
1022                                        if (*next == ',') {
1023                                                indent2 = strtoul(next + 1,
1024                                                                 &next, 10);
1025                                        }
1026                                }
1027                                if (*next != ')')
1028                                        return 0;
1029                        }
1030                        rewrap_message_tail(sb, c, width, indent1, indent2);
1031                        return end - placeholder + 1;
1032                } else
1033                        return 0;
1034        }
1035
1036        /* these depend on the commit */
1037        if (!commit->object.parsed)
1038                parse_object(commit->object.sha1);
1039
1040        switch (placeholder[0]) {
1041        case 'H':               /* commit hash */
1042                strbuf_addstr(sb, sha1_to_hex(commit->object.sha1));
1043                return 1;
1044        case 'h':               /* abbreviated commit hash */
1045                if (add_again(sb, &c->abbrev_commit_hash))
1046                        return 1;
1047                strbuf_addstr(sb, find_unique_abbrev(commit->object.sha1,
1048                                                     c->pretty_ctx->abbrev));
1049                c->abbrev_commit_hash.len = sb->len - c->abbrev_commit_hash.off;
1050                return 1;
1051        case 'T':               /* tree hash */
1052                strbuf_addstr(sb, sha1_to_hex(commit->tree->object.sha1));
1053                return 1;
1054        case 't':               /* abbreviated tree hash */
1055                if (add_again(sb, &c->abbrev_tree_hash))
1056                        return 1;
1057                strbuf_addstr(sb, find_unique_abbrev(commit->tree->object.sha1,
1058                                                     c->pretty_ctx->abbrev));
1059                c->abbrev_tree_hash.len = sb->len - c->abbrev_tree_hash.off;
1060                return 1;
1061        case 'P':               /* parent hashes */
1062                for (p = commit->parents; p; p = p->next) {
1063                        if (p != commit->parents)
1064                                strbuf_addch(sb, ' ');
1065                        strbuf_addstr(sb, sha1_to_hex(p->item->object.sha1));
1066                }
1067                return 1;
1068        case 'p':               /* abbreviated parent hashes */
1069                if (add_again(sb, &c->abbrev_parent_hashes))
1070                        return 1;
1071                for (p = commit->parents; p; p = p->next) {
1072                        if (p != commit->parents)
1073                                strbuf_addch(sb, ' ');
1074                        strbuf_addstr(sb, find_unique_abbrev(
1075                                        p->item->object.sha1,
1076                                        c->pretty_ctx->abbrev));
1077                }
1078                c->abbrev_parent_hashes.len = sb->len -
1079                                              c->abbrev_parent_hashes.off;
1080                return 1;
1081        case 'm':               /* left/right/bottom */
1082                strbuf_addstr(sb, get_revision_mark(NULL, commit));
1083                return 1;
1084        case 'd':
1085                format_decoration(sb, commit);
1086                return 1;
1087        case 'g':               /* reflog info */
1088                switch(placeholder[1]) {
1089                case 'd':       /* reflog selector */
1090                case 'D':
1091                        if (c->pretty_ctx->reflog_info)
1092                                get_reflog_selector(sb,
1093                                                    c->pretty_ctx->reflog_info,
1094                                                    c->pretty_ctx->date_mode,
1095                                                    c->pretty_ctx->date_mode_explicit,
1096                                                    (placeholder[1] == 'd'));
1097                        return 2;
1098                case 's':       /* reflog message */
1099                        if (c->pretty_ctx->reflog_info)
1100                                get_reflog_message(sb, c->pretty_ctx->reflog_info);
1101                        return 2;
1102                case 'n':
1103                case 'N':
1104                case 'e':
1105                case 'E':
1106                        return format_reflog_person(sb,
1107                                                    placeholder[1],
1108                                                    c->pretty_ctx->reflog_info,
1109                                                    c->pretty_ctx->date_mode);
1110                }
1111                return 0;       /* unknown %g placeholder */
1112        case 'N':
1113                if (c->pretty_ctx->show_notes) {
1114                        format_display_notes(commit->object.sha1, sb,
1115                                    get_log_output_encoding(), 0);
1116                        return 1;
1117                }
1118                return 0;
1119        }
1120
1121        if (placeholder[0] == 'G') {
1122                if (!c->commit_signature_parsed)
1123                        parse_commit_signature(c);
1124                switch (placeholder[1]) {
1125                case 'G':
1126                        if (c->signature.gpg_output)
1127                                strbuf_addstr(sb, c->signature.gpg_output);
1128                        break;
1129                case '?':
1130                        switch (c->signature.good_bad) {
1131                        case 'G':
1132                        case 'B':
1133                                strbuf_addch(sb, c->signature.good_bad);
1134                        }
1135                        break;
1136                case 'S':
1137                        if (c->signature.signer)
1138                                strbuf_addstr(sb, c->signature.signer);
1139                        break;
1140                }
1141                return 2;
1142        }
1143
1144
1145        /* For the rest we have to parse the commit header. */
1146        if (!c->commit_header_parsed)
1147                parse_commit_header(c);
1148
1149        switch (placeholder[0]) {
1150        case 'a':       /* author ... */
1151                return format_person_part(sb, placeholder[1],
1152                                   msg + c->author.off, c->author.len,
1153                                   c->pretty_ctx->date_mode);
1154        case 'c':       /* committer ... */
1155                return format_person_part(sb, placeholder[1],
1156                                   msg + c->committer.off, c->committer.len,
1157                                   c->pretty_ctx->date_mode);
1158        case 'e':       /* encoding */
1159                strbuf_add(sb, msg + c->encoding.off, c->encoding.len);
1160                return 1;
1161        case 'B':       /* raw body */
1162                /* message_off is always left at the initial newline */
1163                strbuf_addstr(sb, msg + c->message_off + 1);
1164                return 1;
1165        }
1166
1167        /* Now we need to parse the commit message. */
1168        if (!c->commit_message_parsed)
1169                parse_commit_message(c);
1170
1171        switch (placeholder[0]) {
1172        case 's':       /* subject */
1173                format_subject(sb, msg + c->subject_off, " ");
1174                return 1;
1175        case 'f':       /* sanitized subject */
1176                format_sanitized_subject(sb, msg + c->subject_off);
1177                return 1;
1178        case 'b':       /* body */
1179                strbuf_addstr(sb, msg + c->body_off);
1180                return 1;
1181        }
1182        return 0;       /* unknown placeholder */
1183}
1184
1185static size_t format_commit_item(struct strbuf *sb, const char *placeholder,
1186                                 void *context)
1187{
1188        int consumed;
1189        size_t orig_len;
1190        enum {
1191                NO_MAGIC,
1192                ADD_LF_BEFORE_NON_EMPTY,
1193                DEL_LF_BEFORE_EMPTY,
1194                ADD_SP_BEFORE_NON_EMPTY
1195        } magic = NO_MAGIC;
1196
1197        switch (placeholder[0]) {
1198        case '-':
1199                magic = DEL_LF_BEFORE_EMPTY;
1200                break;
1201        case '+':
1202                magic = ADD_LF_BEFORE_NON_EMPTY;
1203                break;
1204        case ' ':
1205                magic = ADD_SP_BEFORE_NON_EMPTY;
1206                break;
1207        default:
1208                break;
1209        }
1210        if (magic != NO_MAGIC)
1211                placeholder++;
1212
1213        orig_len = sb->len;
1214        consumed = format_commit_one(sb, placeholder, context);
1215        if (magic == NO_MAGIC)
1216                return consumed;
1217
1218        if ((orig_len == sb->len) && magic == DEL_LF_BEFORE_EMPTY) {
1219                while (sb->len && sb->buf[sb->len - 1] == '\n')
1220                        strbuf_setlen(sb, sb->len - 1);
1221        } else if (orig_len != sb->len) {
1222                if (magic == ADD_LF_BEFORE_NON_EMPTY)
1223                        strbuf_insert(sb, orig_len, "\n", 1);
1224                else if (magic == ADD_SP_BEFORE_NON_EMPTY)
1225                        strbuf_insert(sb, orig_len, " ", 1);
1226        }
1227        return consumed + 1;
1228}
1229
1230static size_t userformat_want_item(struct strbuf *sb, const char *placeholder,
1231                                   void *context)
1232{
1233        struct userformat_want *w = context;
1234
1235        if (*placeholder == '+' || *placeholder == '-' || *placeholder == ' ')
1236                placeholder++;
1237
1238        switch (*placeholder) {
1239        case 'N':
1240                w->notes = 1;
1241                break;
1242        }
1243        return 0;
1244}
1245
1246void userformat_find_requirements(const char *fmt, struct userformat_want *w)
1247{
1248        struct strbuf dummy = STRBUF_INIT;
1249
1250        if (!fmt) {
1251                if (!user_format)
1252                        return;
1253                fmt = user_format;
1254        }
1255        strbuf_expand(&dummy, fmt, userformat_want_item, w);
1256        strbuf_release(&dummy);
1257}
1258
1259void format_commit_message(const struct commit *commit,
1260                           const char *format, struct strbuf *sb,
1261                           const struct pretty_print_context *pretty_ctx)
1262{
1263        struct format_commit_context context;
1264        static const char utf8[] = "UTF-8";
1265        const char *output_enc = pretty_ctx->output_encoding;
1266
1267        memset(&context, 0, sizeof(context));
1268        context.commit = commit;
1269        context.pretty_ctx = pretty_ctx;
1270        context.wrap_start = sb->len;
1271        context.message = commit->buffer;
1272        if (output_enc) {
1273                char *enc = get_header(commit, "encoding");
1274                if (strcmp(enc ? enc : utf8, output_enc)) {
1275                        context.message = logmsg_reencode(commit, output_enc);
1276                        if (!context.message)
1277                                context.message = commit->buffer;
1278                }
1279                free(enc);
1280        }
1281
1282        strbuf_expand(sb, format, format_commit_item, &context);
1283        rewrap_message_tail(sb, &context, 0, 0, 0);
1284
1285        if (context.message != commit->buffer)
1286                free(context.message);
1287        free(context.signature.gpg_output);
1288        free(context.signature.signer);
1289}
1290
1291static void pp_header(const struct pretty_print_context *pp,
1292                      const char *encoding,
1293                      const struct commit *commit,
1294                      const char **msg_p,
1295                      struct strbuf *sb)
1296{
1297        int parents_shown = 0;
1298
1299        for (;;) {
1300                const char *line = *msg_p;
1301                int linelen = get_one_line(*msg_p);
1302
1303                if (!linelen)
1304                        return;
1305                *msg_p += linelen;
1306
1307                if (linelen == 1)
1308                        /* End of header */
1309                        return;
1310
1311                if (pp->fmt == CMIT_FMT_RAW) {
1312                        strbuf_add(sb, line, linelen);
1313                        continue;
1314                }
1315
1316                if (!memcmp(line, "parent ", 7)) {
1317                        if (linelen != 48)
1318                                die("bad parent line in commit");
1319                        continue;
1320                }
1321
1322                if (!parents_shown) {
1323                        struct commit_list *parent;
1324                        int num;
1325                        for (parent = commit->parents, num = 0;
1326                             parent;
1327                             parent = parent->next, num++)
1328                                ;
1329                        /* with enough slop */
1330                        strbuf_grow(sb, num * 50 + 20);
1331                        add_merge_info(pp, sb, commit);
1332                        parents_shown = 1;
1333                }
1334
1335                /*
1336                 * MEDIUM == DEFAULT shows only author with dates.
1337                 * FULL shows both authors but not dates.
1338                 * FULLER shows both authors and dates.
1339                 */
1340                if (!memcmp(line, "author ", 7)) {
1341                        strbuf_grow(sb, linelen + 80);
1342                        pp_user_info(pp, "Author", sb, line + 7, encoding);
1343                }
1344                if (!memcmp(line, "committer ", 10) &&
1345                    (pp->fmt == CMIT_FMT_FULL || pp->fmt == CMIT_FMT_FULLER)) {
1346                        strbuf_grow(sb, linelen + 80);
1347                        pp_user_info(pp, "Commit", sb, line + 10, encoding);
1348                }
1349        }
1350}
1351
1352void pp_title_line(const struct pretty_print_context *pp,
1353                   const char **msg_p,
1354                   struct strbuf *sb,
1355                   const char *encoding,
1356                   int need_8bit_cte)
1357{
1358        static const int max_length = 78; /* per rfc2047 */
1359        struct strbuf title;
1360
1361        strbuf_init(&title, 80);
1362        *msg_p = format_subject(&title, *msg_p,
1363                                pp->preserve_subject ? "\n" : " ");
1364
1365        strbuf_grow(sb, title.len + 1024);
1366        if (pp->subject) {
1367                strbuf_addstr(sb, pp->subject);
1368                if (needs_rfc2047_encoding(title.buf, title.len, RFC2047_SUBJECT))
1369                        add_rfc2047(sb, title.buf, title.len,
1370                                                encoding, RFC2047_SUBJECT);
1371                else
1372                        strbuf_add_wrapped_bytes(sb, title.buf, title.len,
1373                                         -last_line_length(sb), 1, max_length);
1374        } else {
1375                strbuf_addbuf(sb, &title);
1376        }
1377        strbuf_addch(sb, '\n');
1378
1379        if (need_8bit_cte > 0) {
1380                const char *header_fmt =
1381                        "MIME-Version: 1.0\n"
1382                        "Content-Type: text/plain; charset=%s\n"
1383                        "Content-Transfer-Encoding: 8bit\n";
1384                strbuf_addf(sb, header_fmt, encoding);
1385        }
1386        if (pp->after_subject) {
1387                strbuf_addstr(sb, pp->after_subject);
1388        }
1389        if (pp->fmt == CMIT_FMT_EMAIL) {
1390                strbuf_addch(sb, '\n');
1391        }
1392        strbuf_release(&title);
1393}
1394
1395void pp_remainder(const struct pretty_print_context *pp,
1396                  const char **msg_p,
1397                  struct strbuf *sb,
1398                  int indent)
1399{
1400        int first = 1;
1401        for (;;) {
1402                const char *line = *msg_p;
1403                int linelen = get_one_line(line);
1404                *msg_p += linelen;
1405
1406                if (!linelen)
1407                        break;
1408
1409                if (is_empty_line(line, &linelen)) {
1410                        if (first)
1411                                continue;
1412                        if (pp->fmt == CMIT_FMT_SHORT)
1413                                break;
1414                }
1415                first = 0;
1416
1417                strbuf_grow(sb, linelen + indent + 20);
1418                if (indent) {
1419                        memset(sb->buf + sb->len, ' ', indent);
1420                        strbuf_setlen(sb, sb->len + indent);
1421                }
1422                strbuf_add(sb, line, linelen);
1423                strbuf_addch(sb, '\n');
1424        }
1425}
1426
1427char *reencode_commit_message(const struct commit *commit, const char **encoding_p)
1428{
1429        const char *encoding;
1430
1431        encoding = get_log_output_encoding();
1432        if (encoding_p)
1433                *encoding_p = encoding;
1434        return logmsg_reencode(commit, encoding);
1435}
1436
1437void pretty_print_commit(const struct pretty_print_context *pp,
1438                         const struct commit *commit,
1439                         struct strbuf *sb)
1440{
1441        unsigned long beginning_of_body;
1442        int indent = 4;
1443        const char *msg = commit->buffer;
1444        char *reencoded;
1445        const char *encoding;
1446        int need_8bit_cte = pp->need_8bit_cte;
1447
1448        if (pp->fmt == CMIT_FMT_USERFORMAT) {
1449                format_commit_message(commit, user_format, sb, pp);
1450                return;
1451        }
1452
1453        reencoded = reencode_commit_message(commit, &encoding);
1454        if (reencoded) {
1455                msg = reencoded;
1456        }
1457
1458        if (pp->fmt == CMIT_FMT_ONELINE || pp->fmt == CMIT_FMT_EMAIL)
1459                indent = 0;
1460
1461        /*
1462         * We need to check and emit Content-type: to mark it
1463         * as 8-bit if we haven't done so.
1464         */
1465        if (pp->fmt == CMIT_FMT_EMAIL && need_8bit_cte == 0) {
1466                int i, ch, in_body;
1467
1468                for (in_body = i = 0; (ch = msg[i]); i++) {
1469                        if (!in_body) {
1470                                /* author could be non 7-bit ASCII but
1471                                 * the log may be so; skip over the
1472                                 * header part first.
1473                                 */
1474                                if (ch == '\n' && msg[i+1] == '\n')
1475                                        in_body = 1;
1476                        }
1477                        else if (non_ascii(ch)) {
1478                                need_8bit_cte = 1;
1479                                break;
1480                        }
1481                }
1482        }
1483
1484        pp_header(pp, encoding, commit, &msg, sb);
1485        if (pp->fmt != CMIT_FMT_ONELINE && !pp->subject) {
1486                strbuf_addch(sb, '\n');
1487        }
1488
1489        /* Skip excess blank lines at the beginning of body, if any... */
1490        msg = skip_empty_lines(msg);
1491
1492        /* These formats treat the title line specially. */
1493        if (pp->fmt == CMIT_FMT_ONELINE || pp->fmt == CMIT_FMT_EMAIL)
1494                pp_title_line(pp, &msg, sb, encoding, need_8bit_cte);
1495
1496        beginning_of_body = sb->len;
1497        if (pp->fmt != CMIT_FMT_ONELINE)
1498                pp_remainder(pp, &msg, sb, indent);
1499        strbuf_rtrim(sb);
1500
1501        /* Make sure there is an EOLN for the non-oneline case */
1502        if (pp->fmt != CMIT_FMT_ONELINE)
1503                strbuf_addch(sb, '\n');
1504
1505        /*
1506         * The caller may append additional body text in e-mail
1507         * format.  Make sure we did not strip the blank line
1508         * between the header and the body.
1509         */
1510        if (pp->fmt == CMIT_FMT_EMAIL && sb->len <= beginning_of_body)
1511                strbuf_addch(sb, '\n');
1512
1513        if (pp->show_notes)
1514                format_display_notes(commit->object.sha1, sb, encoding,
1515                                     NOTES_SHOW_HEADER | NOTES_INDENT);
1516
1517        free(reencoded);
1518}
1519
1520void pp_commit_easy(enum cmit_fmt fmt, const struct commit *commit,
1521                    struct strbuf *sb)
1522{
1523        struct pretty_print_context pp = {0};
1524        pp.fmt = fmt;
1525        pretty_print_commit(&pp, commit, sb);
1526}