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