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