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