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