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