Merge branch 'am/mingw-poll-fix' into maint
[git] / pretty.c
1 #include "cache.h"
2 #include "config.h"
3 #include "commit.h"
4 #include "utf8.h"
5 #include "diff.h"
6 #include "revision.h"
7 #include "string-list.h"
8 #include "mailmap.h"
9 #include "log-tree.h"
10 #include "notes.h"
11 #include "color.h"
12 #include "reflog-walk.h"
13 #include "gpg-interface.h"
14 #include "trailer.h"
15
16 static char *user_format;
17 static struct cmt_fmt_map {
18         const char *name;
19         enum cmit_fmt format;
20         int is_tformat;
21         int expand_tabs_in_log;
22         int is_alias;
23         enum date_mode_type default_date_mode_type;
24         const char *user_format;
25 } *commit_formats;
26 static size_t builtin_formats_len;
27 static size_t commit_formats_len;
28 static size_t commit_formats_alloc;
29 static struct cmt_fmt_map *find_commit_format(const char *sought);
30
31 int commit_format_is_empty(enum cmit_fmt fmt)
32 {
33         return fmt == CMIT_FMT_USERFORMAT && !*user_format;
34 }
35
36 static void save_user_format(struct rev_info *rev, const char *cp, int is_tformat)
37 {
38         free(user_format);
39         user_format = xstrdup(cp);
40         if (is_tformat)
41                 rev->use_terminator = 1;
42         rev->commit_format = CMIT_FMT_USERFORMAT;
43 }
44
45 static int git_pretty_formats_config(const char *var, const char *value, void *cb)
46 {
47         struct cmt_fmt_map *commit_format = NULL;
48         const char *name;
49         const char *fmt;
50         int i;
51
52         if (!skip_prefix(var, "pretty.", &name))
53                 return 0;
54
55         for (i = 0; i < builtin_formats_len; i++) {
56                 if (!strcmp(commit_formats[i].name, name))
57                         return 0;
58         }
59
60         for (i = builtin_formats_len; i < commit_formats_len; i++) {
61                 if (!strcmp(commit_formats[i].name, name)) {
62                         commit_format = &commit_formats[i];
63                         break;
64                 }
65         }
66
67         if (!commit_format) {
68                 ALLOC_GROW(commit_formats, commit_formats_len+1,
69                            commit_formats_alloc);
70                 commit_format = &commit_formats[commit_formats_len];
71                 memset(commit_format, 0, sizeof(*commit_format));
72                 commit_formats_len++;
73         }
74
75         commit_format->name = xstrdup(name);
76         commit_format->format = CMIT_FMT_USERFORMAT;
77         if (git_config_string(&fmt, var, value))
78                 return -1;
79
80         if (skip_prefix(fmt, "format:", &fmt))
81                 commit_format->is_tformat = 0;
82         else if (skip_prefix(fmt, "tformat:", &fmt) || strchr(fmt, '%'))
83                 commit_format->is_tformat = 1;
84         else
85                 commit_format->is_alias = 1;
86         commit_format->user_format = fmt;
87
88         return 0;
89 }
90
91 static void setup_commit_formats(void)
92 {
93         struct cmt_fmt_map builtin_formats[] = {
94                 { "raw",        CMIT_FMT_RAW,           0,      0 },
95                 { "medium",     CMIT_FMT_MEDIUM,        0,      8 },
96                 { "short",      CMIT_FMT_SHORT,         0,      0 },
97                 { "email",      CMIT_FMT_EMAIL,         0,      0 },
98                 { "mboxrd",     CMIT_FMT_MBOXRD,        0,      0 },
99                 { "fuller",     CMIT_FMT_FULLER,        0,      8 },
100                 { "full",       CMIT_FMT_FULL,          0,      8 },
101                 { "oneline",    CMIT_FMT_ONELINE,       1,      0 },
102                 { "reference",  CMIT_FMT_USERFORMAT,    1,      0,
103                         0, DATE_SHORT, "%C(auto)%h (%s, %ad)" },
104                 /*
105                  * Please update $__git_log_pretty_formats in
106                  * git-completion.bash when you add new formats.
107                  */
108         };
109         commit_formats_len = ARRAY_SIZE(builtin_formats);
110         builtin_formats_len = commit_formats_len;
111         ALLOC_GROW(commit_formats, commit_formats_len, commit_formats_alloc);
112         COPY_ARRAY(commit_formats, builtin_formats,
113                    ARRAY_SIZE(builtin_formats));
114
115         git_config(git_pretty_formats_config, NULL);
116 }
117
118 static struct cmt_fmt_map *find_commit_format_recursive(const char *sought,
119                                                         const char *original,
120                                                         int num_redirections)
121 {
122         struct cmt_fmt_map *found = NULL;
123         size_t found_match_len = 0;
124         int i;
125
126         if (num_redirections >= commit_formats_len)
127                 die("invalid --pretty format: "
128                     "'%s' references an alias which points to itself",
129                     original);
130
131         for (i = 0; i < commit_formats_len; i++) {
132                 size_t match_len;
133
134                 if (!starts_with(commit_formats[i].name, sought))
135                         continue;
136
137                 match_len = strlen(commit_formats[i].name);
138                 if (found == NULL || found_match_len > match_len) {
139                         found = &commit_formats[i];
140                         found_match_len = match_len;
141                 }
142         }
143
144         if (found && found->is_alias) {
145                 found = find_commit_format_recursive(found->user_format,
146                                                      original,
147                                                      num_redirections+1);
148         }
149
150         return found;
151 }
152
153 static struct cmt_fmt_map *find_commit_format(const char *sought)
154 {
155         if (!commit_formats)
156                 setup_commit_formats();
157
158         return find_commit_format_recursive(sought, sought, 0);
159 }
160
161 void get_commit_format(const char *arg, struct rev_info *rev)
162 {
163         struct cmt_fmt_map *commit_format;
164
165         rev->use_terminator = 0;
166         if (!arg) {
167                 rev->commit_format = CMIT_FMT_DEFAULT;
168                 return;
169         }
170         if (skip_prefix(arg, "format:", &arg)) {
171                 save_user_format(rev, arg, 0);
172                 return;
173         }
174
175         if (!*arg || skip_prefix(arg, "tformat:", &arg) || strchr(arg, '%')) {
176                 save_user_format(rev, arg, 1);
177                 return;
178         }
179
180         commit_format = find_commit_format(arg);
181         if (!commit_format)
182                 die("invalid --pretty format: %s", arg);
183
184         rev->commit_format = commit_format->format;
185         rev->use_terminator = commit_format->is_tformat;
186         rev->expand_tabs_in_log_default = commit_format->expand_tabs_in_log;
187         if (!rev->date_mode_explicit && commit_format->default_date_mode_type)
188                 rev->date_mode.type = commit_format->default_date_mode_type;
189         if (commit_format->format == CMIT_FMT_USERFORMAT) {
190                 save_user_format(rev, commit_format->user_format,
191                                  commit_format->is_tformat);
192         }
193 }
194
195 /*
196  * Generic support for pretty-printing the header
197  */
198 static int get_one_line(const char *msg)
199 {
200         int ret = 0;
201
202         for (;;) {
203                 char c = *msg++;
204                 if (!c)
205                         break;
206                 ret++;
207                 if (c == '\n')
208                         break;
209         }
210         return ret;
211 }
212
213 /* High bit set, or ISO-2022-INT */
214 static int non_ascii(int ch)
215 {
216         return !isascii(ch) || ch == '\033';
217 }
218
219 int has_non_ascii(const char *s)
220 {
221         int ch;
222         if (!s)
223                 return 0;
224         while ((ch = *s++) != '\0') {
225                 if (non_ascii(ch))
226                         return 1;
227         }
228         return 0;
229 }
230
231 static int is_rfc822_special(char ch)
232 {
233         switch (ch) {
234         case '(':
235         case ')':
236         case '<':
237         case '>':
238         case '[':
239         case ']':
240         case ':':
241         case ';':
242         case '@':
243         case ',':
244         case '.':
245         case '"':
246         case '\\':
247                 return 1;
248         default:
249                 return 0;
250         }
251 }
252
253 static int needs_rfc822_quoting(const char *s, int len)
254 {
255         int i;
256         for (i = 0; i < len; i++)
257                 if (is_rfc822_special(s[i]))
258                         return 1;
259         return 0;
260 }
261
262 static int last_line_length(struct strbuf *sb)
263 {
264         int i;
265
266         /* How many bytes are already used on the last line? */
267         for (i = sb->len - 1; i >= 0; i--)
268                 if (sb->buf[i] == '\n')
269                         break;
270         return sb->len - (i + 1);
271 }
272
273 static void add_rfc822_quoted(struct strbuf *out, const char *s, int len)
274 {
275         int i;
276
277         /* just a guess, we may have to also backslash-quote */
278         strbuf_grow(out, len + 2);
279
280         strbuf_addch(out, '"');
281         for (i = 0; i < len; i++) {
282                 switch (s[i]) {
283                 case '"':
284                 case '\\':
285                         strbuf_addch(out, '\\');
286                         /* fall through */
287                 default:
288                         strbuf_addch(out, s[i]);
289                 }
290         }
291         strbuf_addch(out, '"');
292 }
293
294 enum rfc2047_type {
295         RFC2047_SUBJECT,
296         RFC2047_ADDRESS
297 };
298
299 static int is_rfc2047_special(char ch, enum rfc2047_type type)
300 {
301         /*
302          * rfc2047, section 4.2:
303          *
304          *    8-bit values which correspond to printable ASCII characters other
305          *    than "=", "?", and "_" (underscore), MAY be represented as those
306          *    characters.  (But see section 5 for restrictions.)  In
307          *    particular, SPACE and TAB MUST NOT be represented as themselves
308          *    within encoded words.
309          */
310
311         /*
312          * rule out non-ASCII characters and non-printable characters (the
313          * non-ASCII check should be redundant as isprint() is not localized
314          * and only knows about ASCII, but be defensive about that)
315          */
316         if (non_ascii(ch) || !isprint(ch))
317                 return 1;
318
319         /*
320          * rule out special printable characters (' ' should be the only
321          * whitespace character considered printable, but be defensive and use
322          * isspace())
323          */
324         if (isspace(ch) || ch == '=' || ch == '?' || ch == '_')
325                 return 1;
326
327         /*
328          * rfc2047, section 5.3:
329          *
330          *    As a replacement for a 'word' entity within a 'phrase', for example,
331          *    one that precedes an address in a From, To, or Cc header.  The ABNF
332          *    definition for 'phrase' from RFC 822 thus becomes:
333          *
334          *    phrase = 1*( encoded-word / word )
335          *
336          *    In this case the set of characters that may be used in a "Q"-encoded
337          *    'encoded-word' is restricted to: <upper and lower case ASCII
338          *    letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
339          *    (underscore, ASCII 95.)>.  An 'encoded-word' that appears within a
340          *    'phrase' MUST be separated from any adjacent 'word', 'text' or
341          *    'special' by 'linear-white-space'.
342          */
343
344         if (type != RFC2047_ADDRESS)
345                 return 0;
346
347         /* '=' and '_' are special cases and have been checked above */
348         return !(isalnum(ch) || ch == '!' || ch == '*' || ch == '+' || ch == '-' || ch == '/');
349 }
350
351 static int needs_rfc2047_encoding(const char *line, int len)
352 {
353         int i;
354
355         for (i = 0; i < len; i++) {
356                 int ch = line[i];
357                 if (non_ascii(ch) || ch == '\n')
358                         return 1;
359                 if ((i + 1 < len) && (ch == '=' && line[i+1] == '?'))
360                         return 1;
361         }
362
363         return 0;
364 }
365
366 static void add_rfc2047(struct strbuf *sb, const char *line, size_t len,
367                        const char *encoding, enum rfc2047_type type)
368 {
369         static const int max_encoded_length = 76; /* per rfc2047 */
370         int i;
371         int line_len = last_line_length(sb);
372
373         strbuf_grow(sb, len * 3 + strlen(encoding) + 100);
374         strbuf_addf(sb, "=?%s?q?", encoding);
375         line_len += strlen(encoding) + 5; /* 5 for =??q? */
376
377         while (len) {
378                 /*
379                  * RFC 2047, section 5 (3):
380                  *
381                  * Each 'encoded-word' MUST represent an integral number of
382                  * characters.  A multi-octet character may not be split across
383                  * adjacent 'encoded- word's.
384                  */
385                 const unsigned char *p = (const unsigned char *)line;
386                 int chrlen = mbs_chrlen(&line, &len, encoding);
387                 int is_special = (chrlen > 1) || is_rfc2047_special(*p, type);
388
389                 /* "=%02X" * chrlen, or the byte itself */
390                 const char *encoded_fmt = is_special ? "=%02X"    : "%c";
391                 int         encoded_len = is_special ? 3 * chrlen : 1;
392
393                 /*
394                  * According to RFC 2047, we could encode the special character
395                  * ' ' (space) with '_' (underscore) for readability. But many
396                  * programs do not understand this and just leave the
397                  * underscore in place. Thus, we do nothing special here, which
398                  * causes ' ' to be encoded as '=20', avoiding this problem.
399                  */
400
401                 if (line_len + encoded_len + 2 > max_encoded_length) {
402                         /* It won't fit with trailing "?=" --- break the line */
403                         strbuf_addf(sb, "?=\n =?%s?q?", encoding);
404                         line_len = strlen(encoding) + 5 + 1; /* =??q? plus SP */
405                 }
406
407                 for (i = 0; i < chrlen; i++)
408                         strbuf_addf(sb, encoded_fmt, p[i]);
409                 line_len += encoded_len;
410         }
411         strbuf_addstr(sb, "?=");
412 }
413
414 const char *show_ident_date(const struct ident_split *ident,
415                             const struct date_mode *mode)
416 {
417         timestamp_t date = 0;
418         long tz = 0;
419
420         if (ident->date_begin && ident->date_end)
421                 date = parse_timestamp(ident->date_begin, NULL, 10);
422         if (date_overflows(date))
423                 date = 0;
424         else {
425                 if (ident->tz_begin && ident->tz_end)
426                         tz = strtol(ident->tz_begin, NULL, 10);
427                 if (tz >= INT_MAX || tz <= INT_MIN)
428                         tz = 0;
429         }
430         return show_date(date, tz, mode);
431 }
432
433 void pp_user_info(struct pretty_print_context *pp,
434                   const char *what, struct strbuf *sb,
435                   const char *line, const char *encoding)
436 {
437         struct ident_split ident;
438         char *line_end;
439         const char *mailbuf, *namebuf;
440         size_t namelen, maillen;
441         int max_length = 78; /* per rfc2822 */
442
443         if (pp->fmt == CMIT_FMT_ONELINE)
444                 return;
445
446         line_end = strchrnul(line, '\n');
447         if (split_ident_line(&ident, line, line_end - line))
448                 return;
449
450         mailbuf = ident.mail_begin;
451         maillen = ident.mail_end - ident.mail_begin;
452         namebuf = ident.name_begin;
453         namelen = ident.name_end - ident.name_begin;
454
455         if (pp->mailmap)
456                 map_user(pp->mailmap, &mailbuf, &maillen, &namebuf, &namelen);
457
458         if (cmit_fmt_is_mail(pp->fmt)) {
459                 if (pp->from_ident && ident_cmp(pp->from_ident, &ident)) {
460                         struct strbuf buf = STRBUF_INIT;
461
462                         strbuf_addstr(&buf, "From: ");
463                         strbuf_add(&buf, namebuf, namelen);
464                         strbuf_addstr(&buf, " <");
465                         strbuf_add(&buf, mailbuf, maillen);
466                         strbuf_addstr(&buf, ">\n");
467                         string_list_append(&pp->in_body_headers,
468                                            strbuf_detach(&buf, NULL));
469
470                         mailbuf = pp->from_ident->mail_begin;
471                         maillen = pp->from_ident->mail_end - mailbuf;
472                         namebuf = pp->from_ident->name_begin;
473                         namelen = pp->from_ident->name_end - namebuf;
474                 }
475
476                 strbuf_addstr(sb, "From: ");
477                 if (needs_rfc2047_encoding(namebuf, namelen)) {
478                         add_rfc2047(sb, namebuf, namelen,
479                                     encoding, RFC2047_ADDRESS);
480                         max_length = 76; /* per rfc2047 */
481                 } else if (needs_rfc822_quoting(namebuf, namelen)) {
482                         struct strbuf quoted = STRBUF_INIT;
483                         add_rfc822_quoted(&quoted, namebuf, namelen);
484                         strbuf_add_wrapped_bytes(sb, quoted.buf, quoted.len,
485                                                         -6, 1, max_length);
486                         strbuf_release(&quoted);
487                 } else {
488                         strbuf_add_wrapped_bytes(sb, namebuf, namelen,
489                                                  -6, 1, max_length);
490                 }
491
492                 if (max_length <
493                     last_line_length(sb) + strlen(" <") + maillen + strlen(">"))
494                         strbuf_addch(sb, '\n');
495                 strbuf_addf(sb, " <%.*s>\n", (int)maillen, mailbuf);
496         } else {
497                 strbuf_addf(sb, "%s: %.*s%.*s <%.*s>\n", what,
498                             (pp->fmt == CMIT_FMT_FULLER) ? 4 : 0, "    ",
499                             (int)namelen, namebuf, (int)maillen, mailbuf);
500         }
501
502         switch (pp->fmt) {
503         case CMIT_FMT_MEDIUM:
504                 strbuf_addf(sb, "Date:   %s\n",
505                             show_ident_date(&ident, &pp->date_mode));
506                 break;
507         case CMIT_FMT_EMAIL:
508         case CMIT_FMT_MBOXRD:
509                 strbuf_addf(sb, "Date: %s\n",
510                             show_ident_date(&ident, DATE_MODE(RFC2822)));
511                 break;
512         case CMIT_FMT_FULLER:
513                 strbuf_addf(sb, "%sDate: %s\n", what,
514                             show_ident_date(&ident, &pp->date_mode));
515                 break;
516         default:
517                 /* notin' */
518                 break;
519         }
520 }
521
522 static int is_blank_line(const char *line, int *len_p)
523 {
524         int len = *len_p;
525         while (len && isspace(line[len - 1]))
526                 len--;
527         *len_p = len;
528         return !len;
529 }
530
531 const char *skip_blank_lines(const char *msg)
532 {
533         for (;;) {
534                 int linelen = get_one_line(msg);
535                 int ll = linelen;
536                 if (!linelen)
537                         break;
538                 if (!is_blank_line(msg, &ll))
539                         break;
540                 msg += linelen;
541         }
542         return msg;
543 }
544
545 static void add_merge_info(const struct pretty_print_context *pp,
546                            struct strbuf *sb, const struct commit *commit)
547 {
548         struct commit_list *parent = commit->parents;
549
550         if ((pp->fmt == CMIT_FMT_ONELINE) || (cmit_fmt_is_mail(pp->fmt)) ||
551             !parent || !parent->next)
552                 return;
553
554         strbuf_addstr(sb, "Merge:");
555
556         while (parent) {
557                 struct object_id *oidp = &parent->item->object.oid;
558                 strbuf_addch(sb, ' ');
559                 if (pp->abbrev)
560                         strbuf_add_unique_abbrev(sb, oidp, pp->abbrev);
561                 else
562                         strbuf_addstr(sb, oid_to_hex(oidp));
563                 parent = parent->next;
564         }
565         strbuf_addch(sb, '\n');
566 }
567
568 static char *get_header(const char *msg, const char *key)
569 {
570         size_t len;
571         const char *v = find_commit_header(msg, key, &len);
572         return v ? xmemdupz(v, len) : NULL;
573 }
574
575 static char *replace_encoding_header(char *buf, const char *encoding)
576 {
577         struct strbuf tmp = STRBUF_INIT;
578         size_t start, len;
579         char *cp = buf;
580
581         /* guess if there is an encoding header before a \n\n */
582         while (!starts_with(cp, "encoding ")) {
583                 cp = strchr(cp, '\n');
584                 if (!cp || *++cp == '\n')
585                         return buf;
586         }
587         start = cp - buf;
588         cp = strchr(cp, '\n');
589         if (!cp)
590                 return buf; /* should not happen but be defensive */
591         len = cp + 1 - (buf + start);
592
593         strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
594         if (is_encoding_utf8(encoding)) {
595                 /* we have re-coded to UTF-8; drop the header */
596                 strbuf_remove(&tmp, start, len);
597         } else {
598                 /* just replaces XXXX in 'encoding XXXX\n' */
599                 strbuf_splice(&tmp, start + strlen("encoding "),
600                                           len - strlen("encoding \n"),
601                                           encoding, strlen(encoding));
602         }
603         return strbuf_detach(&tmp, NULL);
604 }
605
606 const char *repo_logmsg_reencode(struct repository *r,
607                                  const struct commit *commit,
608                                  char **commit_encoding,
609                                  const char *output_encoding)
610 {
611         static const char *utf8 = "UTF-8";
612         const char *use_encoding;
613         char *encoding;
614         const char *msg = repo_get_commit_buffer(r, commit, NULL);
615         char *out;
616
617         if (!output_encoding || !*output_encoding) {
618                 if (commit_encoding)
619                         *commit_encoding = get_header(msg, "encoding");
620                 return msg;
621         }
622         encoding = get_header(msg, "encoding");
623         if (commit_encoding)
624                 *commit_encoding = encoding;
625         use_encoding = encoding ? encoding : utf8;
626         if (same_encoding(use_encoding, output_encoding)) {
627                 /*
628                  * No encoding work to be done. If we have no encoding header
629                  * at all, then there's nothing to do, and we can return the
630                  * message verbatim (whether newly allocated or not).
631                  */
632                 if (!encoding)
633                         return msg;
634
635                 /*
636                  * Otherwise, we still want to munge the encoding header in the
637                  * result, which will be done by modifying the buffer. If we
638                  * are using a fresh copy, we can reuse it. But if we are using
639                  * the cached copy from get_commit_buffer, we need to duplicate it
640                  * to avoid munging the cached copy.
641                  */
642                 if (msg == get_cached_commit_buffer(r, commit, NULL))
643                         out = xstrdup(msg);
644                 else
645                         out = (char *)msg;
646         }
647         else {
648                 /*
649                  * There's actual encoding work to do. Do the reencoding, which
650                  * still leaves the header to be replaced in the next step. At
651                  * this point, we are done with msg. If we allocated a fresh
652                  * copy, we can free it.
653                  */
654                 out = reencode_string(msg, output_encoding, use_encoding);
655                 if (out)
656                         repo_unuse_commit_buffer(r, commit, msg);
657         }
658
659         /*
660          * This replacement actually consumes the buffer we hand it, so we do
661          * not have to worry about freeing the old "out" here.
662          */
663         if (out)
664                 out = replace_encoding_header(out, output_encoding);
665
666         if (!commit_encoding)
667                 free(encoding);
668         /*
669          * If the re-encoding failed, out might be NULL here; in that
670          * case we just return the commit message verbatim.
671          */
672         return out ? out : msg;
673 }
674
675 static int mailmap_name(const char **email, size_t *email_len,
676                         const char **name, size_t *name_len)
677 {
678         static struct string_list *mail_map;
679         if (!mail_map) {
680                 mail_map = xcalloc(1, sizeof(*mail_map));
681                 read_mailmap(mail_map, NULL);
682         }
683         return mail_map->nr && map_user(mail_map, email, email_len, name, name_len);
684 }
685
686 static size_t format_person_part(struct strbuf *sb, char part,
687                                  const char *msg, int len,
688                                  const struct date_mode *dmode)
689 {
690         /* currently all placeholders have same length */
691         const int placeholder_len = 2;
692         struct ident_split s;
693         const char *name, *mail;
694         size_t maillen, namelen;
695
696         if (split_ident_line(&s, msg, len) < 0)
697                 goto skip;
698
699         name = s.name_begin;
700         namelen = s.name_end - s.name_begin;
701         mail = s.mail_begin;
702         maillen = s.mail_end - s.mail_begin;
703
704         if (part == 'N' || part == 'E' || part == 'L') /* mailmap lookup */
705                 mailmap_name(&mail, &maillen, &name, &namelen);
706         if (part == 'n' || part == 'N') {       /* name */
707                 strbuf_add(sb, name, namelen);
708                 return placeholder_len;
709         }
710         if (part == 'e' || part == 'E') {       /* email */
711                 strbuf_add(sb, mail, maillen);
712                 return placeholder_len;
713         }
714         if (part == 'l' || part == 'L') {       /* local-part */
715                 const char *at = memchr(mail, '@', maillen);
716                 if (at)
717                         maillen = at - mail;
718                 strbuf_add(sb, mail, maillen);
719                 return placeholder_len;
720         }
721
722         if (!s.date_begin)
723                 goto skip;
724
725         if (part == 't') {      /* date, UNIX timestamp */
726                 strbuf_add(sb, s.date_begin, s.date_end - s.date_begin);
727                 return placeholder_len;
728         }
729
730         switch (part) {
731         case 'd':       /* date */
732                 strbuf_addstr(sb, show_ident_date(&s, dmode));
733                 return placeholder_len;
734         case 'D':       /* date, RFC2822 style */
735                 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RFC2822)));
736                 return placeholder_len;
737         case 'r':       /* date, relative */
738                 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RELATIVE)));
739                 return placeholder_len;
740         case 'i':       /* date, ISO 8601-like */
741                 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601)));
742                 return placeholder_len;
743         case 'I':       /* date, ISO 8601 strict */
744                 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601_STRICT)));
745                 return placeholder_len;
746         case 's':
747                 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(SHORT)));
748                 return placeholder_len;
749         }
750
751 skip:
752         /*
753          * reading from either a bogus commit, or a reflog entry with
754          * %gn, %ge, etc.; 'sb' cannot be updated, but we still need
755          * to compute a valid return value.
756          */
757         if (part == 'n' || part == 'e' || part == 't' || part == 'd'
758             || part == 'D' || part == 'r' || part == 'i')
759                 return placeholder_len;
760
761         return 0; /* unknown placeholder */
762 }
763
764 struct chunk {
765         size_t off;
766         size_t len;
767 };
768
769 enum flush_type {
770         no_flush,
771         flush_right,
772         flush_left,
773         flush_left_and_steal,
774         flush_both
775 };
776
777 enum trunc_type {
778         trunc_none,
779         trunc_left,
780         trunc_middle,
781         trunc_right
782 };
783
784 struct format_commit_context {
785         const struct commit *commit;
786         const struct pretty_print_context *pretty_ctx;
787         unsigned commit_header_parsed:1;
788         unsigned commit_message_parsed:1;
789         struct signature_check signature_check;
790         enum flush_type flush_type;
791         enum trunc_type truncate;
792         const char *message;
793         char *commit_encoding;
794         size_t width, indent1, indent2;
795         int auto_color;
796         int padding;
797
798         /* These offsets are relative to the start of the commit message. */
799         struct chunk author;
800         struct chunk committer;
801         size_t message_off;
802         size_t subject_off;
803         size_t body_off;
804
805         /* The following ones are relative to the result struct strbuf. */
806         size_t wrap_start;
807 };
808
809 static void parse_commit_header(struct format_commit_context *context)
810 {
811         const char *msg = context->message;
812         int i;
813
814         for (i = 0; msg[i]; i++) {
815                 const char *name;
816                 int eol;
817                 for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
818                         ; /* do nothing */
819
820                 if (i == eol) {
821                         break;
822                 } else if (skip_prefix(msg + i, "author ", &name)) {
823                         context->author.off = name - msg;
824                         context->author.len = msg + eol - name;
825                 } else if (skip_prefix(msg + i, "committer ", &name)) {
826                         context->committer.off = name - msg;
827                         context->committer.len = msg + eol - name;
828                 }
829                 i = eol;
830         }
831         context->message_off = i;
832         context->commit_header_parsed = 1;
833 }
834
835 static int istitlechar(char c)
836 {
837         return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
838                 (c >= '0' && c <= '9') || c == '.' || c == '_';
839 }
840
841 static void format_sanitized_subject(struct strbuf *sb, const char *msg)
842 {
843         size_t trimlen;
844         size_t start_len = sb->len;
845         int space = 2;
846
847         for (; *msg && *msg != '\n'; msg++) {
848                 if (istitlechar(*msg)) {
849                         if (space == 1)
850                                 strbuf_addch(sb, '-');
851                         space = 0;
852                         strbuf_addch(sb, *msg);
853                         if (*msg == '.')
854                                 while (*(msg+1) == '.')
855                                         msg++;
856                 } else
857                         space |= 1;
858         }
859
860         /* trim any trailing '.' or '-' characters */
861         trimlen = 0;
862         while (sb->len - trimlen > start_len &&
863                 (sb->buf[sb->len - 1 - trimlen] == '.'
864                 || sb->buf[sb->len - 1 - trimlen] == '-'))
865                 trimlen++;
866         strbuf_remove(sb, sb->len - trimlen, trimlen);
867 }
868
869 const char *format_subject(struct strbuf *sb, const char *msg,
870                            const char *line_separator)
871 {
872         int first = 1;
873
874         for (;;) {
875                 const char *line = msg;
876                 int linelen = get_one_line(line);
877
878                 msg += linelen;
879                 if (!linelen || is_blank_line(line, &linelen))
880                         break;
881
882                 if (!sb)
883                         continue;
884                 strbuf_grow(sb, linelen + 2);
885                 if (!first)
886                         strbuf_addstr(sb, line_separator);
887                 strbuf_add(sb, line, linelen);
888                 first = 0;
889         }
890         return msg;
891 }
892
893 static void parse_commit_message(struct format_commit_context *c)
894 {
895         const char *msg = c->message + c->message_off;
896         const char *start = c->message;
897
898         msg = skip_blank_lines(msg);
899         c->subject_off = msg - start;
900
901         msg = format_subject(NULL, msg, NULL);
902         msg = skip_blank_lines(msg);
903         c->body_off = msg - start;
904
905         c->commit_message_parsed = 1;
906 }
907
908 static void strbuf_wrap(struct strbuf *sb, size_t pos,
909                         size_t width, size_t indent1, size_t indent2)
910 {
911         struct strbuf tmp = STRBUF_INIT;
912
913         if (pos)
914                 strbuf_add(&tmp, sb->buf, pos);
915         strbuf_add_wrapped_text(&tmp, sb->buf + pos,
916                                 (int) indent1, (int) indent2, (int) width);
917         strbuf_swap(&tmp, sb);
918         strbuf_release(&tmp);
919 }
920
921 static void rewrap_message_tail(struct strbuf *sb,
922                                 struct format_commit_context *c,
923                                 size_t new_width, size_t new_indent1,
924                                 size_t new_indent2)
925 {
926         if (c->width == new_width && c->indent1 == new_indent1 &&
927             c->indent2 == new_indent2)
928                 return;
929         if (c->wrap_start < sb->len)
930                 strbuf_wrap(sb, c->wrap_start, c->width, c->indent1, c->indent2);
931         c->wrap_start = sb->len;
932         c->width = new_width;
933         c->indent1 = new_indent1;
934         c->indent2 = new_indent2;
935 }
936
937 static int format_reflog_person(struct strbuf *sb,
938                                 char part,
939                                 struct reflog_walk_info *log,
940                                 const struct date_mode *dmode)
941 {
942         const char *ident;
943
944         if (!log)
945                 return 2;
946
947         ident = get_reflog_ident(log);
948         if (!ident)
949                 return 2;
950
951         return format_person_part(sb, part, ident, strlen(ident), dmode);
952 }
953
954 static size_t parse_color(struct strbuf *sb, /* in UTF-8 */
955                           const char *placeholder,
956                           struct format_commit_context *c)
957 {
958         const char *rest = placeholder;
959         const char *basic_color = NULL;
960
961         if (placeholder[1] == '(') {
962                 const char *begin = placeholder + 2;
963                 const char *end = strchr(begin, ')');
964                 char color[COLOR_MAXLEN];
965
966                 if (!end)
967                         return 0;
968
969                 if (skip_prefix(begin, "auto,", &begin)) {
970                         if (!want_color(c->pretty_ctx->color))
971                                 return end - placeholder + 1;
972                 } else if (skip_prefix(begin, "always,", &begin)) {
973                         /* nothing to do; we do not respect want_color at all */
974                 } else {
975                         /* the default is the same as "auto" */
976                         if (!want_color(c->pretty_ctx->color))
977                                 return end - placeholder + 1;
978                 }
979
980                 if (color_parse_mem(begin, end - begin, color) < 0)
981                         die(_("unable to parse --pretty format"));
982                 strbuf_addstr(sb, color);
983                 return end - placeholder + 1;
984         }
985
986         /*
987          * We handle things like "%C(red)" above; for historical reasons, there
988          * are a few colors that can be specified without parentheses (and
989          * they cannot support things like "auto" or "always" at all).
990          */
991         if (skip_prefix(placeholder + 1, "red", &rest))
992                 basic_color = GIT_COLOR_RED;
993         else if (skip_prefix(placeholder + 1, "green", &rest))
994                 basic_color = GIT_COLOR_GREEN;
995         else if (skip_prefix(placeholder + 1, "blue", &rest))
996                 basic_color = GIT_COLOR_BLUE;
997         else if (skip_prefix(placeholder + 1, "reset", &rest))
998                 basic_color = GIT_COLOR_RESET;
999
1000         if (basic_color && want_color(c->pretty_ctx->color))
1001                 strbuf_addstr(sb, basic_color);
1002
1003         return rest - placeholder;
1004 }
1005
1006 static size_t parse_padding_placeholder(const char *placeholder,
1007                                         struct format_commit_context *c)
1008 {
1009         const char *ch = placeholder;
1010         enum flush_type flush_type;
1011         int to_column = 0;
1012
1013         switch (*ch++) {
1014         case '<':
1015                 flush_type = flush_right;
1016                 break;
1017         case '>':
1018                 if (*ch == '<') {
1019                         flush_type = flush_both;
1020                         ch++;
1021                 } else if (*ch == '>') {
1022                         flush_type = flush_left_and_steal;
1023                         ch++;
1024                 } else
1025                         flush_type = flush_left;
1026                 break;
1027         default:
1028                 return 0;
1029         }
1030
1031         /* the next value means "wide enough to that column" */
1032         if (*ch == '|') {
1033                 to_column = 1;
1034                 ch++;
1035         }
1036
1037         if (*ch == '(') {
1038                 const char *start = ch + 1;
1039                 const char *end = start + strcspn(start, ",)");
1040                 char *next;
1041                 int width;
1042                 if (!end || end == start)
1043                         return 0;
1044                 width = strtol(start, &next, 10);
1045                 if (next == start || width == 0)
1046                         return 0;
1047                 if (width < 0) {
1048                         if (to_column)
1049                                 width += term_columns();
1050                         if (width < 0)
1051                                 return 0;
1052                 }
1053                 c->padding = to_column ? -width : width;
1054                 c->flush_type = flush_type;
1055
1056                 if (*end == ',') {
1057                         start = end + 1;
1058                         end = strchr(start, ')');
1059                         if (!end || end == start)
1060                                 return 0;
1061                         if (starts_with(start, "trunc)"))
1062                                 c->truncate = trunc_right;
1063                         else if (starts_with(start, "ltrunc)"))
1064                                 c->truncate = trunc_left;
1065                         else if (starts_with(start, "mtrunc)"))
1066                                 c->truncate = trunc_middle;
1067                         else
1068                                 return 0;
1069                 } else
1070                         c->truncate = trunc_none;
1071
1072                 return end - placeholder + 1;
1073         }
1074         return 0;
1075 }
1076
1077 static int match_placeholder_arg_value(const char *to_parse, const char *candidate,
1078                                        const char **end, const char **valuestart,
1079                                        size_t *valuelen)
1080 {
1081         const char *p;
1082
1083         if (!(skip_prefix(to_parse, candidate, &p)))
1084                 return 0;
1085         if (valuestart) {
1086                 if (*p == '=') {
1087                         *valuestart = p + 1;
1088                         *valuelen = strcspn(*valuestart, ",)");
1089                         p = *valuestart + *valuelen;
1090                 } else {
1091                         if (*p != ',' && *p != ')')
1092                                 return 0;
1093                         *valuestart = NULL;
1094                         *valuelen = 0;
1095                 }
1096         }
1097         if (*p == ',') {
1098                 *end = p + 1;
1099                 return 1;
1100         }
1101         if (*p == ')') {
1102                 *end = p;
1103                 return 1;
1104         }
1105         return 0;
1106 }
1107
1108 static int match_placeholder_bool_arg(const char *to_parse, const char *candidate,
1109                                       const char **end, int *val)
1110 {
1111         const char *argval;
1112         char *strval;
1113         size_t arglen;
1114         int v;
1115
1116         if (!match_placeholder_arg_value(to_parse, candidate, end, &argval, &arglen))
1117                 return 0;
1118
1119         if (!argval) {
1120                 *val = 1;
1121                 return 1;
1122         }
1123
1124         strval = xstrndup(argval, arglen);
1125         v = git_parse_maybe_bool(strval);
1126         free(strval);
1127
1128         if (v == -1)
1129                 return 0;
1130
1131         *val = v;
1132
1133         return 1;
1134 }
1135
1136 static int format_trailer_match_cb(const struct strbuf *key, void *ud)
1137 {
1138         const struct string_list *list = ud;
1139         const struct string_list_item *item;
1140
1141         for_each_string_list_item (item, list) {
1142                 if (key->len == (uintptr_t)item->util &&
1143                     !strncasecmp(item->string, key->buf, key->len))
1144                         return 1;
1145         }
1146         return 0;
1147 }
1148
1149 static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
1150                                 const char *placeholder,
1151                                 void *context)
1152 {
1153         struct format_commit_context *c = context;
1154         const struct commit *commit = c->commit;
1155         const char *msg = c->message;
1156         struct commit_list *p;
1157         const char *arg;
1158         size_t res;
1159         char **slot;
1160
1161         /* these are independent of the commit */
1162         res = strbuf_expand_literal_cb(sb, placeholder, NULL);
1163         if (res)
1164                 return res;
1165
1166         switch (placeholder[0]) {
1167         case 'C':
1168                 if (starts_with(placeholder + 1, "(auto)")) {
1169                         c->auto_color = want_color(c->pretty_ctx->color);
1170                         if (c->auto_color && sb->len)
1171                                 strbuf_addstr(sb, GIT_COLOR_RESET);
1172                         return 7; /* consumed 7 bytes, "C(auto)" */
1173                 } else {
1174                         int ret = parse_color(sb, placeholder, c);
1175                         if (ret)
1176                                 c->auto_color = 0;
1177                         /*
1178                          * Otherwise, we decided to treat %C<unknown>
1179                          * as a literal string, and the previous
1180                          * %C(auto) is still valid.
1181                          */
1182                         return ret;
1183                 }
1184         case 'w':
1185                 if (placeholder[1] == '(') {
1186                         unsigned long width = 0, indent1 = 0, indent2 = 0;
1187                         char *next;
1188                         const char *start = placeholder + 2;
1189                         const char *end = strchr(start, ')');
1190                         if (!end)
1191                                 return 0;
1192                         if (end > start) {
1193                                 width = strtoul(start, &next, 10);
1194                                 if (*next == ',') {
1195                                         indent1 = strtoul(next + 1, &next, 10);
1196                                         if (*next == ',') {
1197                                                 indent2 = strtoul(next + 1,
1198                                                                  &next, 10);
1199                                         }
1200                                 }
1201                                 if (*next != ')')
1202                                         return 0;
1203                         }
1204                         rewrap_message_tail(sb, c, width, indent1, indent2);
1205                         return end - placeholder + 1;
1206                 } else
1207                         return 0;
1208
1209         case '<':
1210         case '>':
1211                 return parse_padding_placeholder(placeholder, c);
1212         }
1213
1214         /* these depend on the commit */
1215         if (!commit->object.parsed)
1216                 parse_object(the_repository, &commit->object.oid);
1217
1218         switch (placeholder[0]) {
1219         case 'H':               /* commit hash */
1220                 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1221                 strbuf_addstr(sb, oid_to_hex(&commit->object.oid));
1222                 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1223                 return 1;
1224         case 'h':               /* abbreviated commit hash */
1225                 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1226                 strbuf_add_unique_abbrev(sb, &commit->object.oid,
1227                                          c->pretty_ctx->abbrev);
1228                 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1229                 return 1;
1230         case 'T':               /* tree hash */
1231                 strbuf_addstr(sb, oid_to_hex(get_commit_tree_oid(commit)));
1232                 return 1;
1233         case 't':               /* abbreviated tree hash */
1234                 strbuf_add_unique_abbrev(sb,
1235                                          get_commit_tree_oid(commit),
1236                                          c->pretty_ctx->abbrev);
1237                 return 1;
1238         case 'P':               /* parent hashes */
1239                 for (p = commit->parents; p; p = p->next) {
1240                         if (p != commit->parents)
1241                                 strbuf_addch(sb, ' ');
1242                         strbuf_addstr(sb, oid_to_hex(&p->item->object.oid));
1243                 }
1244                 return 1;
1245         case 'p':               /* abbreviated parent hashes */
1246                 for (p = commit->parents; p; p = p->next) {
1247                         if (p != commit->parents)
1248                                 strbuf_addch(sb, ' ');
1249                         strbuf_add_unique_abbrev(sb, &p->item->object.oid,
1250                                                  c->pretty_ctx->abbrev);
1251                 }
1252                 return 1;
1253         case 'm':               /* left/right/bottom */
1254                 strbuf_addstr(sb, get_revision_mark(NULL, commit));
1255                 return 1;
1256         case 'd':
1257                 format_decorations(sb, commit, c->auto_color);
1258                 return 1;
1259         case 'D':
1260                 format_decorations_extended(sb, commit, c->auto_color, "", ", ", "");
1261                 return 1;
1262         case 'S':               /* tag/branch like --source */
1263                 if (!(c->pretty_ctx->rev && c->pretty_ctx->rev->sources))
1264                         return 0;
1265                 slot = revision_sources_at(c->pretty_ctx->rev->sources, commit);
1266                 if (!(slot && *slot))
1267                         return 0;
1268                 strbuf_addstr(sb, *slot);
1269                 return 1;
1270         case 'g':               /* reflog info */
1271                 switch(placeholder[1]) {
1272                 case 'd':       /* reflog selector */
1273                 case 'D':
1274                         if (c->pretty_ctx->reflog_info)
1275                                 get_reflog_selector(sb,
1276                                                     c->pretty_ctx->reflog_info,
1277                                                     &c->pretty_ctx->date_mode,
1278                                                     c->pretty_ctx->date_mode_explicit,
1279                                                     (placeholder[1] == 'd'));
1280                         return 2;
1281                 case 's':       /* reflog message */
1282                         if (c->pretty_ctx->reflog_info)
1283                                 get_reflog_message(sb, c->pretty_ctx->reflog_info);
1284                         return 2;
1285                 case 'n':
1286                 case 'N':
1287                 case 'e':
1288                 case 'E':
1289                         return format_reflog_person(sb,
1290                                                     placeholder[1],
1291                                                     c->pretty_ctx->reflog_info,
1292                                                     &c->pretty_ctx->date_mode);
1293                 }
1294                 return 0;       /* unknown %g placeholder */
1295         case 'N':
1296                 if (c->pretty_ctx->notes_message) {
1297                         strbuf_addstr(sb, c->pretty_ctx->notes_message);
1298                         return 1;
1299                 }
1300                 return 0;
1301         }
1302
1303         if (placeholder[0] == 'G') {
1304                 if (!c->signature_check.result)
1305                         check_commit_signature(c->commit, &(c->signature_check));
1306                 switch (placeholder[1]) {
1307                 case 'G':
1308                         if (c->signature_check.gpg_output)
1309                                 strbuf_addstr(sb, c->signature_check.gpg_output);
1310                         break;
1311                 case '?':
1312                         switch (c->signature_check.result) {
1313                         case 'G':
1314                         case 'B':
1315                         case 'E':
1316                         case 'U':
1317                         case 'N':
1318                         case 'X':
1319                         case 'Y':
1320                         case 'R':
1321                                 strbuf_addch(sb, c->signature_check.result);
1322                         }
1323                         break;
1324                 case 'S':
1325                         if (c->signature_check.signer)
1326                                 strbuf_addstr(sb, c->signature_check.signer);
1327                         break;
1328                 case 'K':
1329                         if (c->signature_check.key)
1330                                 strbuf_addstr(sb, c->signature_check.key);
1331                         break;
1332                 case 'F':
1333                         if (c->signature_check.fingerprint)
1334                                 strbuf_addstr(sb, c->signature_check.fingerprint);
1335                         break;
1336                 case 'P':
1337                         if (c->signature_check.primary_key_fingerprint)
1338                                 strbuf_addstr(sb, c->signature_check.primary_key_fingerprint);
1339                         break;
1340                 default:
1341                         return 0;
1342                 }
1343                 return 2;
1344         }
1345
1346
1347         /* For the rest we have to parse the commit header. */
1348         if (!c->commit_header_parsed)
1349                 parse_commit_header(c);
1350
1351         switch (placeholder[0]) {
1352         case 'a':       /* author ... */
1353                 return format_person_part(sb, placeholder[1],
1354                                    msg + c->author.off, c->author.len,
1355                                    &c->pretty_ctx->date_mode);
1356         case 'c':       /* committer ... */
1357                 return format_person_part(sb, placeholder[1],
1358                                    msg + c->committer.off, c->committer.len,
1359                                    &c->pretty_ctx->date_mode);
1360         case 'e':       /* encoding */
1361                 if (c->commit_encoding)
1362                         strbuf_addstr(sb, c->commit_encoding);
1363                 return 1;
1364         case 'B':       /* raw body */
1365                 /* message_off is always left at the initial newline */
1366                 strbuf_addstr(sb, msg + c->message_off + 1);
1367                 return 1;
1368         }
1369
1370         /* Now we need to parse the commit message. */
1371         if (!c->commit_message_parsed)
1372                 parse_commit_message(c);
1373
1374         switch (placeholder[0]) {
1375         case 's':       /* subject */
1376                 format_subject(sb, msg + c->subject_off, " ");
1377                 return 1;
1378         case 'f':       /* sanitized subject */
1379                 format_sanitized_subject(sb, msg + c->subject_off);
1380                 return 1;
1381         case 'b':       /* body */
1382                 strbuf_addstr(sb, msg + c->body_off);
1383                 return 1;
1384         }
1385
1386         if (skip_prefix(placeholder, "(trailers", &arg)) {
1387                 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1388                 struct string_list filter_list = STRING_LIST_INIT_NODUP;
1389                 struct strbuf sepbuf = STRBUF_INIT;
1390                 size_t ret = 0;
1391
1392                 opts.no_divider = 1;
1393
1394                 if (*arg == ':') {
1395                         arg++;
1396                         for (;;) {
1397                                 const char *argval;
1398                                 size_t arglen;
1399
1400                                 if (match_placeholder_arg_value(arg, "key", &arg, &argval, &arglen)) {
1401                                         uintptr_t len = arglen;
1402
1403                                         if (!argval)
1404                                                 goto trailer_out;
1405
1406                                         if (len && argval[len - 1] == ':')
1407                                                 len--;
1408                                         string_list_append(&filter_list, argval)->util = (char *)len;
1409
1410                                         opts.filter = format_trailer_match_cb;
1411                                         opts.filter_data = &filter_list;
1412                                         opts.only_trailers = 1;
1413                                 } else if (match_placeholder_arg_value(arg, "separator", &arg, &argval, &arglen)) {
1414                                         char *fmt;
1415
1416                                         strbuf_reset(&sepbuf);
1417                                         fmt = xstrndup(argval, arglen);
1418                                         strbuf_expand(&sepbuf, fmt, strbuf_expand_literal_cb, NULL);
1419                                         free(fmt);
1420                                         opts.separator = &sepbuf;
1421                                 } else if (!match_placeholder_bool_arg(arg, "only", &arg, &opts.only_trailers) &&
1422                                            !match_placeholder_bool_arg(arg, "unfold", &arg, &opts.unfold) &&
1423                                            !match_placeholder_bool_arg(arg, "valueonly", &arg, &opts.value_only))
1424                                         break;
1425                         }
1426                 }
1427                 if (*arg == ')') {
1428                         format_trailers_from_commit(sb, msg + c->subject_off, &opts);
1429                         ret = arg - placeholder + 1;
1430                 }
1431         trailer_out:
1432                 string_list_clear(&filter_list, 0);
1433                 strbuf_release(&sepbuf);
1434                 return ret;
1435         }
1436
1437         return 0;       /* unknown placeholder */
1438 }
1439
1440 static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */
1441                                     const char *placeholder,
1442                                     struct format_commit_context *c)
1443 {
1444         struct strbuf local_sb = STRBUF_INIT;
1445         int total_consumed = 0, len, padding = c->padding;
1446         if (padding < 0) {
1447                 const char *start = strrchr(sb->buf, '\n');
1448                 int occupied;
1449                 if (!start)
1450                         start = sb->buf;
1451                 occupied = utf8_strnwidth(start, -1, 1);
1452                 occupied += c->pretty_ctx->graph_width;
1453                 padding = (-padding) - occupied;
1454         }
1455         while (1) {
1456                 int modifier = *placeholder == 'C';
1457                 int consumed = format_commit_one(&local_sb, placeholder, c);
1458                 total_consumed += consumed;
1459
1460                 if (!modifier)
1461                         break;
1462
1463                 placeholder += consumed;
1464                 if (*placeholder != '%')
1465                         break;
1466                 placeholder++;
1467                 total_consumed++;
1468         }
1469         len = utf8_strnwidth(local_sb.buf, -1, 1);
1470
1471         if (c->flush_type == flush_left_and_steal) {
1472                 const char *ch = sb->buf + sb->len - 1;
1473                 while (len > padding && ch > sb->buf) {
1474                         const char *p;
1475                         if (*ch == ' ') {
1476                                 ch--;
1477                                 padding++;
1478                                 continue;
1479                         }
1480                         /* check for trailing ansi sequences */
1481                         if (*ch != 'm')
1482                                 break;
1483                         p = ch - 1;
1484                         while (ch - p < 10 && *p != '\033')
1485                                 p--;
1486                         if (*p != '\033' ||
1487                             ch + 1 - p != display_mode_esc_sequence_len(p))
1488                                 break;
1489                         /*
1490                          * got a good ansi sequence, put it back to
1491                          * local_sb as we're cutting sb
1492                          */
1493                         strbuf_insert(&local_sb, 0, p, ch + 1 - p);
1494                         ch = p - 1;
1495                 }
1496                 strbuf_setlen(sb, ch + 1 - sb->buf);
1497                 c->flush_type = flush_left;
1498         }
1499
1500         if (len > padding) {
1501                 switch (c->truncate) {
1502                 case trunc_left:
1503                         strbuf_utf8_replace(&local_sb,
1504                                             0, len - (padding - 2),
1505                                             "..");
1506                         break;
1507                 case trunc_middle:
1508                         strbuf_utf8_replace(&local_sb,
1509                                             padding / 2 - 1,
1510                                             len - (padding - 2),
1511                                             "..");
1512                         break;
1513                 case trunc_right:
1514                         strbuf_utf8_replace(&local_sb,
1515                                             padding - 2, len - (padding - 2),
1516                                             "..");
1517                         break;
1518                 case trunc_none:
1519                         break;
1520                 }
1521                 strbuf_addbuf(sb, &local_sb);
1522         } else {
1523                 int sb_len = sb->len, offset = 0;
1524                 if (c->flush_type == flush_left)
1525                         offset = padding - len;
1526                 else if (c->flush_type == flush_both)
1527                         offset = (padding - len) / 2;
1528                 /*
1529                  * we calculate padding in columns, now
1530                  * convert it back to chars
1531                  */
1532                 padding = padding - len + local_sb.len;
1533                 strbuf_addchars(sb, ' ', padding);
1534                 memcpy(sb->buf + sb_len + offset, local_sb.buf,
1535                        local_sb.len);
1536         }
1537         strbuf_release(&local_sb);
1538         c->flush_type = no_flush;
1539         return total_consumed;
1540 }
1541
1542 static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */
1543                                  const char *placeholder,
1544                                  void *context)
1545 {
1546         int consumed;
1547         size_t orig_len;
1548         enum {
1549                 NO_MAGIC,
1550                 ADD_LF_BEFORE_NON_EMPTY,
1551                 DEL_LF_BEFORE_EMPTY,
1552                 ADD_SP_BEFORE_NON_EMPTY
1553         } magic = NO_MAGIC;
1554
1555         switch (placeholder[0]) {
1556         case '-':
1557                 magic = DEL_LF_BEFORE_EMPTY;
1558                 break;
1559         case '+':
1560                 magic = ADD_LF_BEFORE_NON_EMPTY;
1561                 break;
1562         case ' ':
1563                 magic = ADD_SP_BEFORE_NON_EMPTY;
1564                 break;
1565         default:
1566                 break;
1567         }
1568         if (magic != NO_MAGIC)
1569                 placeholder++;
1570
1571         orig_len = sb->len;
1572         if (((struct format_commit_context *)context)->flush_type != no_flush)
1573                 consumed = format_and_pad_commit(sb, placeholder, context);
1574         else
1575                 consumed = format_commit_one(sb, placeholder, context);
1576         if (magic == NO_MAGIC)
1577                 return consumed;
1578
1579         if ((orig_len == sb->len) && magic == DEL_LF_BEFORE_EMPTY) {
1580                 while (sb->len && sb->buf[sb->len - 1] == '\n')
1581                         strbuf_setlen(sb, sb->len - 1);
1582         } else if (orig_len != sb->len) {
1583                 if (magic == ADD_LF_BEFORE_NON_EMPTY)
1584                         strbuf_insert(sb, orig_len, "\n", 1);
1585                 else if (magic == ADD_SP_BEFORE_NON_EMPTY)
1586                         strbuf_insert(sb, orig_len, " ", 1);
1587         }
1588         return consumed + 1;
1589 }
1590
1591 static size_t userformat_want_item(struct strbuf *sb, const char *placeholder,
1592                                    void *context)
1593 {
1594         struct userformat_want *w = context;
1595
1596         if (*placeholder == '+' || *placeholder == '-' || *placeholder == ' ')
1597                 placeholder++;
1598
1599         switch (*placeholder) {
1600         case 'N':
1601                 w->notes = 1;
1602                 break;
1603         case 'S':
1604                 w->source = 1;
1605                 break;
1606         }
1607         return 0;
1608 }
1609
1610 void userformat_find_requirements(const char *fmt, struct userformat_want *w)
1611 {
1612         struct strbuf dummy = STRBUF_INIT;
1613
1614         if (!fmt) {
1615                 if (!user_format)
1616                         return;
1617                 fmt = user_format;
1618         }
1619         strbuf_expand(&dummy, fmt, userformat_want_item, w);
1620         strbuf_release(&dummy);
1621 }
1622
1623 void repo_format_commit_message(struct repository *r,
1624                                 const struct commit *commit,
1625                                 const char *format, struct strbuf *sb,
1626                                 const struct pretty_print_context *pretty_ctx)
1627 {
1628         struct format_commit_context context = {
1629                 .commit = commit,
1630                 .pretty_ctx = pretty_ctx,
1631                 .wrap_start = sb->len
1632         };
1633         const char *output_enc = pretty_ctx->output_encoding;
1634         const char *utf8 = "UTF-8";
1635
1636         /*
1637          * convert a commit message to UTF-8 first
1638          * as far as 'format_commit_item' assumes it in UTF-8
1639          */
1640         context.message = repo_logmsg_reencode(r, commit,
1641                                                &context.commit_encoding,
1642                                                utf8);
1643
1644         strbuf_expand(sb, format, format_commit_item, &context);
1645         rewrap_message_tail(sb, &context, 0, 0, 0);
1646
1647         /* then convert a commit message to an actual output encoding */
1648         if (output_enc) {
1649                 if (same_encoding(utf8, output_enc))
1650                         output_enc = NULL;
1651         } else {
1652                 if (context.commit_encoding &&
1653                     !same_encoding(context.commit_encoding, utf8))
1654                         output_enc = context.commit_encoding;
1655         }
1656
1657         if (output_enc) {
1658                 size_t outsz;
1659                 char *out = reencode_string_len(sb->buf, sb->len,
1660                                                 output_enc, utf8, &outsz);
1661                 if (out)
1662                         strbuf_attach(sb, out, outsz, outsz + 1);
1663         }
1664
1665         free(context.commit_encoding);
1666         repo_unuse_commit_buffer(r, commit, context.message);
1667 }
1668
1669 static void pp_header(struct pretty_print_context *pp,
1670                       const char *encoding,
1671                       const struct commit *commit,
1672                       const char **msg_p,
1673                       struct strbuf *sb)
1674 {
1675         int parents_shown = 0;
1676
1677         for (;;) {
1678                 const char *name, *line = *msg_p;
1679                 int linelen = get_one_line(*msg_p);
1680
1681                 if (!linelen)
1682                         return;
1683                 *msg_p += linelen;
1684
1685                 if (linelen == 1)
1686                         /* End of header */
1687                         return;
1688
1689                 if (pp->fmt == CMIT_FMT_RAW) {
1690                         strbuf_add(sb, line, linelen);
1691                         continue;
1692                 }
1693
1694                 if (starts_with(line, "parent ")) {
1695                         if (linelen != the_hash_algo->hexsz + 8)
1696                                 die("bad parent line in commit");
1697                         continue;
1698                 }
1699
1700                 if (!parents_shown) {
1701                         unsigned num = commit_list_count(commit->parents);
1702                         /* with enough slop */
1703                         strbuf_grow(sb, num * (GIT_MAX_HEXSZ + 10) + 20);
1704                         add_merge_info(pp, sb, commit);
1705                         parents_shown = 1;
1706                 }
1707
1708                 /*
1709                  * MEDIUM == DEFAULT shows only author with dates.
1710                  * FULL shows both authors but not dates.
1711                  * FULLER shows both authors and dates.
1712                  */
1713                 if (skip_prefix(line, "author ", &name)) {
1714                         strbuf_grow(sb, linelen + 80);
1715                         pp_user_info(pp, "Author", sb, name, encoding);
1716                 }
1717                 if (skip_prefix(line, "committer ", &name) &&
1718                     (pp->fmt == CMIT_FMT_FULL || pp->fmt == CMIT_FMT_FULLER)) {
1719                         strbuf_grow(sb, linelen + 80);
1720                         pp_user_info(pp, "Commit", sb, name, encoding);
1721                 }
1722         }
1723 }
1724
1725 void pp_title_line(struct pretty_print_context *pp,
1726                    const char **msg_p,
1727                    struct strbuf *sb,
1728                    const char *encoding,
1729                    int need_8bit_cte)
1730 {
1731         static const int max_length = 78; /* per rfc2047 */
1732         struct strbuf title;
1733
1734         strbuf_init(&title, 80);
1735         *msg_p = format_subject(&title, *msg_p,
1736                                 pp->preserve_subject ? "\n" : " ");
1737
1738         strbuf_grow(sb, title.len + 1024);
1739         if (pp->print_email_subject) {
1740                 if (pp->rev)
1741                         fmt_output_email_subject(sb, pp->rev);
1742                 if (needs_rfc2047_encoding(title.buf, title.len))
1743                         add_rfc2047(sb, title.buf, title.len,
1744                                                 encoding, RFC2047_SUBJECT);
1745                 else
1746                         strbuf_add_wrapped_bytes(sb, title.buf, title.len,
1747                                          -last_line_length(sb), 1, max_length);
1748         } else {
1749                 strbuf_addbuf(sb, &title);
1750         }
1751         strbuf_addch(sb, '\n');
1752
1753         if (need_8bit_cte == 0) {
1754                 int i;
1755                 for (i = 0; i < pp->in_body_headers.nr; i++) {
1756                         if (has_non_ascii(pp->in_body_headers.items[i].string)) {
1757                                 need_8bit_cte = 1;
1758                                 break;
1759                         }
1760                 }
1761         }
1762
1763         if (need_8bit_cte > 0) {
1764                 const char *header_fmt =
1765                         "MIME-Version: 1.0\n"
1766                         "Content-Type: text/plain; charset=%s\n"
1767                         "Content-Transfer-Encoding: 8bit\n";
1768                 strbuf_addf(sb, header_fmt, encoding);
1769         }
1770         if (pp->after_subject) {
1771                 strbuf_addstr(sb, pp->after_subject);
1772         }
1773         if (cmit_fmt_is_mail(pp->fmt)) {
1774                 strbuf_addch(sb, '\n');
1775         }
1776
1777         if (pp->in_body_headers.nr) {
1778                 int i;
1779                 for (i = 0; i < pp->in_body_headers.nr; i++) {
1780                         strbuf_addstr(sb, pp->in_body_headers.items[i].string);
1781                         free(pp->in_body_headers.items[i].string);
1782                 }
1783                 string_list_clear(&pp->in_body_headers, 0);
1784                 strbuf_addch(sb, '\n');
1785         }
1786
1787         strbuf_release(&title);
1788 }
1789
1790 static int pp_utf8_width(const char *start, const char *end)
1791 {
1792         int width = 0;
1793         size_t remain = end - start;
1794
1795         while (remain) {
1796                 int n = utf8_width(&start, &remain);
1797                 if (n < 0 || !start)
1798                         return -1;
1799                 width += n;
1800         }
1801         return width;
1802 }
1803
1804 static void strbuf_add_tabexpand(struct strbuf *sb, int tabwidth,
1805                                  const char *line, int linelen)
1806 {
1807         const char *tab;
1808
1809         while ((tab = memchr(line, '\t', linelen)) != NULL) {
1810                 int width = pp_utf8_width(line, tab);
1811
1812                 /*
1813                  * If it wasn't well-formed utf8, or it
1814                  * had characters with badly defined
1815                  * width (control characters etc), just
1816                  * give up on trying to align things.
1817                  */
1818                 if (width < 0)
1819                         break;
1820
1821                 /* Output the data .. */
1822                 strbuf_add(sb, line, tab - line);
1823
1824                 /* .. and the de-tabified tab */
1825                 strbuf_addchars(sb, ' ', tabwidth - (width % tabwidth));
1826
1827                 /* Skip over the printed part .. */
1828                 linelen -= tab + 1 - line;
1829                 line = tab + 1;
1830         }
1831
1832         /*
1833          * Print out everything after the last tab without
1834          * worrying about width - there's nothing more to
1835          * align.
1836          */
1837         strbuf_add(sb, line, linelen);
1838 }
1839
1840 /*
1841  * pp_handle_indent() prints out the intendation, and
1842  * the whole line (without the final newline), after
1843  * de-tabifying.
1844  */
1845 static void pp_handle_indent(struct pretty_print_context *pp,
1846                              struct strbuf *sb, int indent,
1847                              const char *line, int linelen)
1848 {
1849         strbuf_addchars(sb, ' ', indent);
1850         if (pp->expand_tabs_in_log)
1851                 strbuf_add_tabexpand(sb, pp->expand_tabs_in_log, line, linelen);
1852         else
1853                 strbuf_add(sb, line, linelen);
1854 }
1855
1856 static int is_mboxrd_from(const char *line, int len)
1857 {
1858         /*
1859          * a line matching /^From $/ here would only have len == 4
1860          * at this point because is_empty_line would've trimmed all
1861          * trailing space
1862          */
1863         return len > 4 && starts_with(line + strspn(line, ">"), "From ");
1864 }
1865
1866 void pp_remainder(struct pretty_print_context *pp,
1867                   const char **msg_p,
1868                   struct strbuf *sb,
1869                   int indent)
1870 {
1871         int first = 1;
1872         for (;;) {
1873                 const char *line = *msg_p;
1874                 int linelen = get_one_line(line);
1875                 *msg_p += linelen;
1876
1877                 if (!linelen)
1878                         break;
1879
1880                 if (is_blank_line(line, &linelen)) {
1881                         if (first)
1882                                 continue;
1883                         if (pp->fmt == CMIT_FMT_SHORT)
1884                                 break;
1885                 }
1886                 first = 0;
1887
1888                 strbuf_grow(sb, linelen + indent + 20);
1889                 if (indent)
1890                         pp_handle_indent(pp, sb, indent, line, linelen);
1891                 else if (pp->expand_tabs_in_log)
1892                         strbuf_add_tabexpand(sb, pp->expand_tabs_in_log,
1893                                              line, linelen);
1894                 else {
1895                         if (pp->fmt == CMIT_FMT_MBOXRD &&
1896                                         is_mboxrd_from(line, linelen))
1897                                 strbuf_addch(sb, '>');
1898
1899                         strbuf_add(sb, line, linelen);
1900                 }
1901                 strbuf_addch(sb, '\n');
1902         }
1903 }
1904
1905 void pretty_print_commit(struct pretty_print_context *pp,
1906                          const struct commit *commit,
1907                          struct strbuf *sb)
1908 {
1909         unsigned long beginning_of_body;
1910         int indent = 4;
1911         const char *msg;
1912         const char *reencoded;
1913         const char *encoding;
1914         int need_8bit_cte = pp->need_8bit_cte;
1915
1916         if (pp->fmt == CMIT_FMT_USERFORMAT) {
1917                 format_commit_message(commit, user_format, sb, pp);
1918                 return;
1919         }
1920
1921         encoding = get_log_output_encoding();
1922         msg = reencoded = logmsg_reencode(commit, NULL, encoding);
1923
1924         if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
1925                 indent = 0;
1926
1927         /*
1928          * We need to check and emit Content-type: to mark it
1929          * as 8-bit if we haven't done so.
1930          */
1931         if (cmit_fmt_is_mail(pp->fmt) && need_8bit_cte == 0) {
1932                 int i, ch, in_body;
1933
1934                 for (in_body = i = 0; (ch = msg[i]); i++) {
1935                         if (!in_body) {
1936                                 /* author could be non 7-bit ASCII but
1937                                  * the log may be so; skip over the
1938                                  * header part first.
1939                                  */
1940                                 if (ch == '\n' && msg[i+1] == '\n')
1941                                         in_body = 1;
1942                         }
1943                         else if (non_ascii(ch)) {
1944                                 need_8bit_cte = 1;
1945                                 break;
1946                         }
1947                 }
1948         }
1949
1950         pp_header(pp, encoding, commit, &msg, sb);
1951         if (pp->fmt != CMIT_FMT_ONELINE && !pp->print_email_subject) {
1952                 strbuf_addch(sb, '\n');
1953         }
1954
1955         /* Skip excess blank lines at the beginning of body, if any... */
1956         msg = skip_blank_lines(msg);
1957
1958         /* These formats treat the title line specially. */
1959         if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
1960                 pp_title_line(pp, &msg, sb, encoding, need_8bit_cte);
1961
1962         beginning_of_body = sb->len;
1963         if (pp->fmt != CMIT_FMT_ONELINE)
1964                 pp_remainder(pp, &msg, sb, indent);
1965         strbuf_rtrim(sb);
1966
1967         /* Make sure there is an EOLN for the non-oneline case */
1968         if (pp->fmt != CMIT_FMT_ONELINE)
1969                 strbuf_addch(sb, '\n');
1970
1971         /*
1972          * The caller may append additional body text in e-mail
1973          * format.  Make sure we did not strip the blank line
1974          * between the header and the body.
1975          */
1976         if (cmit_fmt_is_mail(pp->fmt) && sb->len <= beginning_of_body)
1977                 strbuf_addch(sb, '\n');
1978
1979         unuse_commit_buffer(commit, reencoded);
1980 }
1981
1982 void pp_commit_easy(enum cmit_fmt fmt, const struct commit *commit,
1983                     struct strbuf *sb)
1984 {
1985         struct pretty_print_context pp = {0};
1986         pp.fmt = fmt;
1987         pretty_print_commit(&pp, commit, sb);
1988 }