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