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