strbuf: use skip_prefix() in strbuf_addftime()
[git/gitster.git] / pretty.c
blob9e48d521b4f28a9a0935ed3d4b6da8b43985c490
1 #include "git-compat-util.h"
2 #include "alloc.h"
3 #include "config.h"
4 #include "commit.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hash.h"
8 #include "hex.h"
9 #include "utf8.h"
10 #include "diff.h"
11 #include "pager.h"
12 #include "revision.h"
13 #include "string-list.h"
14 #include "mailmap.h"
15 #include "log-tree.h"
16 #include "notes.h"
17 #include "color.h"
18 #include "reflog-walk.h"
19 #include "gpg-interface.h"
20 #include "trailer.h"
21 #include "run-command.h"
24 * The limit for formatting directives, which enable the caller to append
25 * arbitrarily many bytes to the formatted buffer. This includes padding
26 * and wrapping formatters.
28 #define FORMATTING_LIMIT (16 * 1024)
30 static char *user_format;
31 static struct cmt_fmt_map {
32 const char *name;
33 enum cmit_fmt format;
34 int is_tformat;
35 int expand_tabs_in_log;
36 int is_alias;
37 enum date_mode_type default_date_mode_type;
38 const char *user_format;
39 } *commit_formats;
40 static size_t builtin_formats_len;
41 static size_t commit_formats_len;
42 static size_t commit_formats_alloc;
43 static struct cmt_fmt_map *find_commit_format(const char *sought);
45 int commit_format_is_empty(enum cmit_fmt fmt)
47 return fmt == CMIT_FMT_USERFORMAT && !*user_format;
50 static void save_user_format(struct rev_info *rev, const char *cp, int is_tformat)
52 free(user_format);
53 user_format = xstrdup(cp);
54 if (is_tformat)
55 rev->use_terminator = 1;
56 rev->commit_format = CMIT_FMT_USERFORMAT;
59 static int git_pretty_formats_config(const char *var, const char *value,
60 void *cb UNUSED)
62 struct cmt_fmt_map *commit_format = NULL;
63 const char *name;
64 const char *fmt;
65 int i;
67 if (!skip_prefix(var, "pretty.", &name))
68 return 0;
70 for (i = 0; i < builtin_formats_len; i++) {
71 if (!strcmp(commit_formats[i].name, name))
72 return 0;
75 for (i = builtin_formats_len; i < commit_formats_len; i++) {
76 if (!strcmp(commit_formats[i].name, name)) {
77 commit_format = &commit_formats[i];
78 break;
82 if (!commit_format) {
83 ALLOC_GROW(commit_formats, commit_formats_len+1,
84 commit_formats_alloc);
85 commit_format = &commit_formats[commit_formats_len];
86 memset(commit_format, 0, sizeof(*commit_format));
87 commit_formats_len++;
90 commit_format->name = xstrdup(name);
91 commit_format->format = CMIT_FMT_USERFORMAT;
92 if (git_config_string(&fmt, var, value))
93 return -1;
95 if (skip_prefix(fmt, "format:", &fmt))
96 commit_format->is_tformat = 0;
97 else if (skip_prefix(fmt, "tformat:", &fmt) || strchr(fmt, '%'))
98 commit_format->is_tformat = 1;
99 else
100 commit_format->is_alias = 1;
101 commit_format->user_format = fmt;
103 return 0;
106 static void setup_commit_formats(void)
108 struct cmt_fmt_map builtin_formats[] = {
109 { "raw", CMIT_FMT_RAW, 0, 0 },
110 { "medium", CMIT_FMT_MEDIUM, 0, 8 },
111 { "short", CMIT_FMT_SHORT, 0, 0 },
112 { "email", CMIT_FMT_EMAIL, 0, 0 },
113 { "mboxrd", CMIT_FMT_MBOXRD, 0, 0 },
114 { "fuller", CMIT_FMT_FULLER, 0, 8 },
115 { "full", CMIT_FMT_FULL, 0, 8 },
116 { "oneline", CMIT_FMT_ONELINE, 1, 0 },
117 { "reference", CMIT_FMT_USERFORMAT, 1, 0,
118 0, DATE_SHORT, "%C(auto)%h (%s, %ad)" },
120 * Please update $__git_log_pretty_formats in
121 * git-completion.bash when you add new formats.
124 commit_formats_len = ARRAY_SIZE(builtin_formats);
125 builtin_formats_len = commit_formats_len;
126 ALLOC_GROW(commit_formats, commit_formats_len, commit_formats_alloc);
127 COPY_ARRAY(commit_formats, builtin_formats,
128 ARRAY_SIZE(builtin_formats));
130 git_config(git_pretty_formats_config, NULL);
133 static struct cmt_fmt_map *find_commit_format_recursive(const char *sought,
134 const char *original,
135 int num_redirections)
137 struct cmt_fmt_map *found = NULL;
138 size_t found_match_len = 0;
139 int i;
141 if (num_redirections >= commit_formats_len)
142 die("invalid --pretty format: "
143 "'%s' references an alias which points to itself",
144 original);
146 for (i = 0; i < commit_formats_len; i++) {
147 size_t match_len;
149 if (!starts_with(commit_formats[i].name, sought))
150 continue;
152 match_len = strlen(commit_formats[i].name);
153 if (found == NULL || found_match_len > match_len) {
154 found = &commit_formats[i];
155 found_match_len = match_len;
159 if (found && found->is_alias) {
160 found = find_commit_format_recursive(found->user_format,
161 original,
162 num_redirections+1);
165 return found;
168 static struct cmt_fmt_map *find_commit_format(const char *sought)
170 if (!commit_formats)
171 setup_commit_formats();
173 return find_commit_format_recursive(sought, sought, 0);
176 void get_commit_format(const char *arg, struct rev_info *rev)
178 struct cmt_fmt_map *commit_format;
180 rev->use_terminator = 0;
181 if (!arg) {
182 rev->commit_format = CMIT_FMT_DEFAULT;
183 return;
185 if (skip_prefix(arg, "format:", &arg)) {
186 save_user_format(rev, arg, 0);
187 return;
190 if (!*arg || skip_prefix(arg, "tformat:", &arg) || strchr(arg, '%')) {
191 save_user_format(rev, arg, 1);
192 return;
195 commit_format = find_commit_format(arg);
196 if (!commit_format)
197 die("invalid --pretty format: %s", arg);
199 rev->commit_format = commit_format->format;
200 rev->use_terminator = commit_format->is_tformat;
201 rev->expand_tabs_in_log_default = commit_format->expand_tabs_in_log;
202 if (!rev->date_mode_explicit && commit_format->default_date_mode_type)
203 rev->date_mode.type = commit_format->default_date_mode_type;
204 if (commit_format->format == CMIT_FMT_USERFORMAT) {
205 save_user_format(rev, commit_format->user_format,
206 commit_format->is_tformat);
211 * Generic support for pretty-printing the header
213 static int get_one_line(const char *msg)
215 int ret = 0;
217 for (;;) {
218 char c = *msg++;
219 if (!c)
220 break;
221 ret++;
222 if (c == '\n')
223 break;
225 return ret;
228 /* High bit set, or ISO-2022-INT */
229 static int non_ascii(int ch)
231 return !isascii(ch) || ch == '\033';
234 int has_non_ascii(const char *s)
236 int ch;
237 if (!s)
238 return 0;
239 while ((ch = *s++) != '\0') {
240 if (non_ascii(ch))
241 return 1;
243 return 0;
246 static int is_rfc822_special(char ch)
248 switch (ch) {
249 case '(':
250 case ')':
251 case '<':
252 case '>':
253 case '[':
254 case ']':
255 case ':':
256 case ';':
257 case '@':
258 case ',':
259 case '.':
260 case '"':
261 case '\\':
262 return 1;
263 default:
264 return 0;
268 static int needs_rfc822_quoting(const char *s, int len)
270 int i;
271 for (i = 0; i < len; i++)
272 if (is_rfc822_special(s[i]))
273 return 1;
274 return 0;
277 static int last_line_length(struct strbuf *sb)
279 int i;
281 /* How many bytes are already used on the last line? */
282 for (i = sb->len - 1; i >= 0; i--)
283 if (sb->buf[i] == '\n')
284 break;
285 return sb->len - (i + 1);
288 static void add_rfc822_quoted(struct strbuf *out, const char *s, int len)
290 int i;
292 /* just a guess, we may have to also backslash-quote */
293 strbuf_grow(out, len + 2);
295 strbuf_addch(out, '"');
296 for (i = 0; i < len; i++) {
297 switch (s[i]) {
298 case '"':
299 case '\\':
300 strbuf_addch(out, '\\');
301 /* fall through */
302 default:
303 strbuf_addch(out, s[i]);
306 strbuf_addch(out, '"');
309 enum rfc2047_type {
310 RFC2047_SUBJECT,
311 RFC2047_ADDRESS
314 static int is_rfc2047_special(char ch, enum rfc2047_type type)
317 * rfc2047, section 4.2:
319 * 8-bit values which correspond to printable ASCII characters other
320 * than "=", "?", and "_" (underscore), MAY be represented as those
321 * characters. (But see section 5 for restrictions.) In
322 * particular, SPACE and TAB MUST NOT be represented as themselves
323 * within encoded words.
327 * rule out non-ASCII characters and non-printable characters (the
328 * non-ASCII check should be redundant as isprint() is not localized
329 * and only knows about ASCII, but be defensive about that)
331 if (non_ascii(ch) || !isprint(ch))
332 return 1;
335 * rule out special printable characters (' ' should be the only
336 * whitespace character considered printable, but be defensive and use
337 * isspace())
339 if (isspace(ch) || ch == '=' || ch == '?' || ch == '_')
340 return 1;
343 * rfc2047, section 5.3:
345 * As a replacement for a 'word' entity within a 'phrase', for example,
346 * one that precedes an address in a From, To, or Cc header. The ABNF
347 * definition for 'phrase' from RFC 822 thus becomes:
349 * phrase = 1*( encoded-word / word )
351 * In this case the set of characters that may be used in a "Q"-encoded
352 * 'encoded-word' is restricted to: <upper and lower case ASCII
353 * letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
354 * (underscore, ASCII 95.)>. An 'encoded-word' that appears within a
355 * 'phrase' MUST be separated from any adjacent 'word', 'text' or
356 * 'special' by 'linear-white-space'.
359 if (type != RFC2047_ADDRESS)
360 return 0;
362 /* '=' and '_' are special cases and have been checked above */
363 return !(isalnum(ch) || ch == '!' || ch == '*' || ch == '+' || ch == '-' || ch == '/');
366 static int needs_rfc2047_encoding(const char *line, int len)
368 int i;
370 for (i = 0; i < len; i++) {
371 int ch = line[i];
372 if (non_ascii(ch) || ch == '\n')
373 return 1;
374 if ((i + 1 < len) && (ch == '=' && line[i+1] == '?'))
375 return 1;
378 return 0;
381 static void add_rfc2047(struct strbuf *sb, const char *line, size_t len,
382 const char *encoding, enum rfc2047_type type)
384 static const int max_encoded_length = 76; /* per rfc2047 */
385 int i;
386 int line_len = last_line_length(sb);
388 strbuf_grow(sb, len * 3 + strlen(encoding) + 100);
389 strbuf_addf(sb, "=?%s?q?", encoding);
390 line_len += strlen(encoding) + 5; /* 5 for =??q? */
392 while (len) {
394 * RFC 2047, section 5 (3):
396 * Each 'encoded-word' MUST represent an integral number of
397 * characters. A multi-octet character may not be split across
398 * adjacent 'encoded- word's.
400 const unsigned char *p = (const unsigned char *)line;
401 int chrlen = mbs_chrlen(&line, &len, encoding);
402 int is_special = (chrlen > 1) || is_rfc2047_special(*p, type);
404 /* "=%02X" * chrlen, or the byte itself */
405 const char *encoded_fmt = is_special ? "=%02X" : "%c";
406 int encoded_len = is_special ? 3 * chrlen : 1;
409 * According to RFC 2047, we could encode the special character
410 * ' ' (space) with '_' (underscore) for readability. But many
411 * programs do not understand this and just leave the
412 * underscore in place. Thus, we do nothing special here, which
413 * causes ' ' to be encoded as '=20', avoiding this problem.
416 if (line_len + encoded_len + 2 > max_encoded_length) {
417 /* It won't fit with trailing "?=" --- break the line */
418 strbuf_addf(sb, "?=\n =?%s?q?", encoding);
419 line_len = strlen(encoding) + 5 + 1; /* =??q? plus SP */
422 for (i = 0; i < chrlen; i++)
423 strbuf_addf(sb, encoded_fmt, p[i]);
424 line_len += encoded_len;
426 strbuf_addstr(sb, "?=");
429 const char *show_ident_date(const struct ident_split *ident,
430 const struct date_mode *mode)
432 timestamp_t date = 0;
433 long tz = 0;
435 if (ident->date_begin && ident->date_end)
436 date = parse_timestamp(ident->date_begin, NULL, 10);
437 if (date_overflows(date))
438 date = 0;
439 else {
440 if (ident->tz_begin && ident->tz_end)
441 tz = strtol(ident->tz_begin, NULL, 10);
442 if (tz >= INT_MAX || tz <= INT_MIN)
443 tz = 0;
445 return show_date(date, tz, mode);
448 static inline void strbuf_add_with_color(struct strbuf *sb, const char *color,
449 const char *buf, size_t buflen)
451 strbuf_addstr(sb, color);
452 strbuf_add(sb, buf, buflen);
453 if (*color)
454 strbuf_addstr(sb, GIT_COLOR_RESET);
457 static void append_line_with_color(struct strbuf *sb, struct grep_opt *opt,
458 const char *line, size_t linelen,
459 int color, enum grep_context ctx,
460 enum grep_header_field field)
462 const char *buf, *eol, *line_color, *match_color;
463 regmatch_t match;
464 int eflags = 0;
466 buf = line;
467 eol = buf + linelen;
469 if (!opt || !want_color(color) || opt->invert)
470 goto end;
472 line_color = opt->colors[GREP_COLOR_SELECTED];
473 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
475 while (grep_next_match(opt, buf, eol, ctx, &match, field, eflags)) {
476 if (match.rm_so == match.rm_eo)
477 break;
479 strbuf_add_with_color(sb, line_color, buf, match.rm_so);
480 strbuf_add_with_color(sb, match_color, buf + match.rm_so,
481 match.rm_eo - match.rm_so);
482 buf += match.rm_eo;
483 eflags = REG_NOTBOL;
486 if (eflags)
487 strbuf_add_with_color(sb, line_color, buf, eol - buf);
488 else {
489 end:
490 strbuf_add(sb, buf, eol - buf);
494 static int use_in_body_from(const struct pretty_print_context *pp,
495 const struct ident_split *ident)
497 if (pp->rev && pp->rev->force_in_body_from)
498 return 1;
499 if (ident_cmp(pp->from_ident, ident))
500 return 1;
501 return 0;
504 void pp_user_info(struct pretty_print_context *pp,
505 const char *what, struct strbuf *sb,
506 const char *line, const char *encoding)
508 struct ident_split ident;
509 char *line_end;
510 const char *mailbuf, *namebuf;
511 size_t namelen, maillen;
512 int max_length = 78; /* per rfc2822 */
514 if (pp->fmt == CMIT_FMT_ONELINE)
515 return;
517 line_end = strchrnul(line, '\n');
518 if (split_ident_line(&ident, line, line_end - line))
519 return;
521 mailbuf = ident.mail_begin;
522 maillen = ident.mail_end - ident.mail_begin;
523 namebuf = ident.name_begin;
524 namelen = ident.name_end - ident.name_begin;
526 if (pp->mailmap)
527 map_user(pp->mailmap, &mailbuf, &maillen, &namebuf, &namelen);
529 if (cmit_fmt_is_mail(pp->fmt)) {
530 if (pp->from_ident && use_in_body_from(pp, &ident)) {
531 struct strbuf buf = STRBUF_INIT;
533 strbuf_addstr(&buf, "From: ");
534 strbuf_add(&buf, namebuf, namelen);
535 strbuf_addstr(&buf, " <");
536 strbuf_add(&buf, mailbuf, maillen);
537 strbuf_addstr(&buf, ">\n");
538 string_list_append(&pp->in_body_headers,
539 strbuf_detach(&buf, NULL));
541 mailbuf = pp->from_ident->mail_begin;
542 maillen = pp->from_ident->mail_end - mailbuf;
543 namebuf = pp->from_ident->name_begin;
544 namelen = pp->from_ident->name_end - namebuf;
547 strbuf_addstr(sb, "From: ");
548 if (pp->encode_email_headers &&
549 needs_rfc2047_encoding(namebuf, namelen)) {
550 add_rfc2047(sb, namebuf, namelen,
551 encoding, RFC2047_ADDRESS);
552 max_length = 76; /* per rfc2047 */
553 } else if (needs_rfc822_quoting(namebuf, namelen)) {
554 struct strbuf quoted = STRBUF_INIT;
555 add_rfc822_quoted(&quoted, namebuf, namelen);
556 strbuf_add_wrapped_bytes(sb, quoted.buf, quoted.len,
557 -6, 1, max_length);
558 strbuf_release(&quoted);
559 } else {
560 strbuf_add_wrapped_bytes(sb, namebuf, namelen,
561 -6, 1, max_length);
564 if (max_length <
565 last_line_length(sb) + strlen(" <") + maillen + strlen(">"))
566 strbuf_addch(sb, '\n');
567 strbuf_addf(sb, " <%.*s>\n", (int)maillen, mailbuf);
568 } else {
569 struct strbuf id = STRBUF_INIT;
570 enum grep_header_field field = GREP_HEADER_FIELD_MAX;
571 struct grep_opt *opt = pp->rev ? &pp->rev->grep_filter : NULL;
573 if (!strcmp(what, "Author"))
574 field = GREP_HEADER_AUTHOR;
575 else if (!strcmp(what, "Commit"))
576 field = GREP_HEADER_COMMITTER;
578 strbuf_addf(sb, "%s: ", what);
579 if (pp->fmt == CMIT_FMT_FULLER)
580 strbuf_addchars(sb, ' ', 4);
582 strbuf_addf(&id, "%.*s <%.*s>", (int)namelen, namebuf,
583 (int)maillen, mailbuf);
585 append_line_with_color(sb, opt, id.buf, id.len, pp->color,
586 GREP_CONTEXT_HEAD, field);
587 strbuf_addch(sb, '\n');
588 strbuf_release(&id);
591 switch (pp->fmt) {
592 case CMIT_FMT_MEDIUM:
593 strbuf_addf(sb, "Date: %s\n",
594 show_ident_date(&ident, &pp->date_mode));
595 break;
596 case CMIT_FMT_EMAIL:
597 case CMIT_FMT_MBOXRD:
598 strbuf_addf(sb, "Date: %s\n",
599 show_ident_date(&ident, DATE_MODE(RFC2822)));
600 break;
601 case CMIT_FMT_FULLER:
602 strbuf_addf(sb, "%sDate: %s\n", what,
603 show_ident_date(&ident, &pp->date_mode));
604 break;
605 default:
606 /* notin' */
607 break;
611 static int is_blank_line(const char *line, int *len_p)
613 int len = *len_p;
614 while (len && isspace(line[len - 1]))
615 len--;
616 *len_p = len;
617 return !len;
620 const char *skip_blank_lines(const char *msg)
622 for (;;) {
623 int linelen = get_one_line(msg);
624 int ll = linelen;
625 if (!linelen)
626 break;
627 if (!is_blank_line(msg, &ll))
628 break;
629 msg += linelen;
631 return msg;
634 static void add_merge_info(const struct pretty_print_context *pp,
635 struct strbuf *sb, const struct commit *commit)
637 struct commit_list *parent = commit->parents;
639 if ((pp->fmt == CMIT_FMT_ONELINE) || (cmit_fmt_is_mail(pp->fmt)) ||
640 !parent || !parent->next)
641 return;
643 strbuf_addstr(sb, "Merge:");
645 while (parent) {
646 struct object_id *oidp = &parent->item->object.oid;
647 strbuf_addch(sb, ' ');
648 if (pp->abbrev)
649 strbuf_add_unique_abbrev(sb, oidp, pp->abbrev);
650 else
651 strbuf_addstr(sb, oid_to_hex(oidp));
652 parent = parent->next;
654 strbuf_addch(sb, '\n');
657 static char *get_header(const char *msg, const char *key)
659 size_t len;
660 const char *v = find_commit_header(msg, key, &len);
661 return v ? xmemdupz(v, len) : NULL;
664 static char *replace_encoding_header(char *buf, const char *encoding)
666 struct strbuf tmp = STRBUF_INIT;
667 size_t start, len;
668 char *cp = buf;
670 /* guess if there is an encoding header before a \n\n */
671 while (!starts_with(cp, "encoding ")) {
672 cp = strchr(cp, '\n');
673 if (!cp || *++cp == '\n')
674 return buf;
676 start = cp - buf;
677 cp = strchr(cp, '\n');
678 if (!cp)
679 return buf; /* should not happen but be defensive */
680 len = cp + 1 - (buf + start);
682 strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
683 if (is_encoding_utf8(encoding)) {
684 /* we have re-coded to UTF-8; drop the header */
685 strbuf_remove(&tmp, start, len);
686 } else {
687 /* just replaces XXXX in 'encoding XXXX\n' */
688 strbuf_splice(&tmp, start + strlen("encoding "),
689 len - strlen("encoding \n"),
690 encoding, strlen(encoding));
692 return strbuf_detach(&tmp, NULL);
695 const char *repo_logmsg_reencode(struct repository *r,
696 const struct commit *commit,
697 char **commit_encoding,
698 const char *output_encoding)
700 static const char *utf8 = "UTF-8";
701 const char *use_encoding;
702 char *encoding;
703 const char *msg = repo_get_commit_buffer(r, commit, NULL);
704 char *out;
706 if (!output_encoding || !*output_encoding) {
707 if (commit_encoding)
708 *commit_encoding = get_header(msg, "encoding");
709 return msg;
711 encoding = get_header(msg, "encoding");
712 if (commit_encoding)
713 *commit_encoding = encoding;
714 use_encoding = encoding ? encoding : utf8;
715 if (same_encoding(use_encoding, output_encoding)) {
717 * No encoding work to be done. If we have no encoding header
718 * at all, then there's nothing to do, and we can return the
719 * message verbatim (whether newly allocated or not).
721 if (!encoding)
722 return msg;
725 * Otherwise, we still want to munge the encoding header in the
726 * result, which will be done by modifying the buffer. If we
727 * are using a fresh copy, we can reuse it. But if we are using
728 * the cached copy from repo_get_commit_buffer, we need to duplicate it
729 * to avoid munging the cached copy.
731 if (msg == get_cached_commit_buffer(r, commit, NULL))
732 out = xstrdup(msg);
733 else
734 out = (char *)msg;
736 else {
738 * There's actual encoding work to do. Do the reencoding, which
739 * still leaves the header to be replaced in the next step. At
740 * this point, we are done with msg. If we allocated a fresh
741 * copy, we can free it.
743 out = reencode_string(msg, output_encoding, use_encoding);
744 if (out)
745 repo_unuse_commit_buffer(r, commit, msg);
749 * This replacement actually consumes the buffer we hand it, so we do
750 * not have to worry about freeing the old "out" here.
752 if (out)
753 out = replace_encoding_header(out, output_encoding);
755 if (!commit_encoding)
756 free(encoding);
758 * If the re-encoding failed, out might be NULL here; in that
759 * case we just return the commit message verbatim.
761 return out ? out : msg;
764 static int mailmap_name(const char **email, size_t *email_len,
765 const char **name, size_t *name_len)
767 static struct string_list *mail_map;
768 if (!mail_map) {
769 CALLOC_ARRAY(mail_map, 1);
770 read_mailmap(mail_map);
772 return mail_map->nr && map_user(mail_map, email, email_len, name, name_len);
775 static size_t format_person_part(struct strbuf *sb, char part,
776 const char *msg, int len,
777 const struct date_mode *dmode)
779 /* currently all placeholders have same length */
780 const int placeholder_len = 2;
781 struct ident_split s;
782 const char *name, *mail;
783 size_t maillen, namelen;
785 if (split_ident_line(&s, msg, len) < 0)
786 goto skip;
788 name = s.name_begin;
789 namelen = s.name_end - s.name_begin;
790 mail = s.mail_begin;
791 maillen = s.mail_end - s.mail_begin;
793 if (part == 'N' || part == 'E' || part == 'L') /* mailmap lookup */
794 mailmap_name(&mail, &maillen, &name, &namelen);
795 if (part == 'n' || part == 'N') { /* name */
796 strbuf_add(sb, name, namelen);
797 return placeholder_len;
799 if (part == 'e' || part == 'E') { /* email */
800 strbuf_add(sb, mail, maillen);
801 return placeholder_len;
803 if (part == 'l' || part == 'L') { /* local-part */
804 const char *at = memchr(mail, '@', maillen);
805 if (at)
806 maillen = at - mail;
807 strbuf_add(sb, mail, maillen);
808 return placeholder_len;
811 if (!s.date_begin)
812 goto skip;
814 if (part == 't') { /* date, UNIX timestamp */
815 strbuf_add(sb, s.date_begin, s.date_end - s.date_begin);
816 return placeholder_len;
819 switch (part) {
820 case 'd': /* date */
821 strbuf_addstr(sb, show_ident_date(&s, dmode));
822 return placeholder_len;
823 case 'D': /* date, RFC2822 style */
824 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RFC2822)));
825 return placeholder_len;
826 case 'r': /* date, relative */
827 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RELATIVE)));
828 return placeholder_len;
829 case 'i': /* date, ISO 8601-like */
830 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601)));
831 return placeholder_len;
832 case 'I': /* date, ISO 8601 strict */
833 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601_STRICT)));
834 return placeholder_len;
835 case 'h': /* date, human */
836 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(HUMAN)));
837 return placeholder_len;
838 case 's':
839 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(SHORT)));
840 return placeholder_len;
843 skip:
845 * reading from either a bogus commit, or a reflog entry with
846 * %gn, %ge, etc.; 'sb' cannot be updated, but we still need
847 * to compute a valid return value.
849 if (part == 'n' || part == 'e' || part == 't' || part == 'd'
850 || part == 'D' || part == 'r' || part == 'i')
851 return placeholder_len;
853 return 0; /* unknown placeholder */
856 struct chunk {
857 size_t off;
858 size_t len;
861 enum flush_type {
862 no_flush,
863 flush_right,
864 flush_left,
865 flush_left_and_steal,
866 flush_both
869 enum trunc_type {
870 trunc_none,
871 trunc_left,
872 trunc_middle,
873 trunc_right
876 struct format_commit_context {
877 struct repository *repository;
878 const struct commit *commit;
879 const struct pretty_print_context *pretty_ctx;
880 unsigned commit_header_parsed:1;
881 unsigned commit_message_parsed:1;
882 struct signature_check signature_check;
883 enum flush_type flush_type;
884 enum trunc_type truncate;
885 const char *message;
886 char *commit_encoding;
887 size_t width, indent1, indent2;
888 int auto_color;
889 int padding;
891 /* These offsets are relative to the start of the commit message. */
892 struct chunk author;
893 struct chunk committer;
894 size_t message_off;
895 size_t subject_off;
896 size_t body_off;
898 /* The following ones are relative to the result struct strbuf. */
899 size_t wrap_start;
902 static void parse_commit_header(struct format_commit_context *context)
904 const char *msg = context->message;
905 int i;
907 for (i = 0; msg[i]; i++) {
908 const char *name;
909 int eol;
910 for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
911 ; /* do nothing */
913 if (i == eol) {
914 break;
915 } else if (skip_prefix(msg + i, "author ", &name)) {
916 context->author.off = name - msg;
917 context->author.len = msg + eol - name;
918 } else if (skip_prefix(msg + i, "committer ", &name)) {
919 context->committer.off = name - msg;
920 context->committer.len = msg + eol - name;
922 i = eol;
924 context->message_off = i;
925 context->commit_header_parsed = 1;
928 static int istitlechar(char c)
930 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
931 (c >= '0' && c <= '9') || c == '.' || c == '_';
934 void format_sanitized_subject(struct strbuf *sb, const char *msg, size_t len)
936 size_t trimlen;
937 size_t start_len = sb->len;
938 int space = 2;
939 int i;
941 for (i = 0; i < len; i++) {
942 if (istitlechar(msg[i])) {
943 if (space == 1)
944 strbuf_addch(sb, '-');
945 space = 0;
946 strbuf_addch(sb, msg[i]);
947 if (msg[i] == '.')
948 while (msg[i+1] == '.')
949 i++;
950 } else
951 space |= 1;
954 /* trim any trailing '.' or '-' characters */
955 trimlen = 0;
956 while (sb->len - trimlen > start_len &&
957 (sb->buf[sb->len - 1 - trimlen] == '.'
958 || sb->buf[sb->len - 1 - trimlen] == '-'))
959 trimlen++;
960 strbuf_remove(sb, sb->len - trimlen, trimlen);
963 const char *format_subject(struct strbuf *sb, const char *msg,
964 const char *line_separator)
966 int first = 1;
968 for (;;) {
969 const char *line = msg;
970 int linelen = get_one_line(line);
972 msg += linelen;
973 if (!linelen || is_blank_line(line, &linelen))
974 break;
976 if (!sb)
977 continue;
978 strbuf_grow(sb, linelen + 2);
979 if (!first)
980 strbuf_addstr(sb, line_separator);
981 strbuf_add(sb, line, linelen);
982 first = 0;
984 return msg;
987 static void parse_commit_message(struct format_commit_context *c)
989 const char *msg = c->message + c->message_off;
990 const char *start = c->message;
992 msg = skip_blank_lines(msg);
993 c->subject_off = msg - start;
995 msg = format_subject(NULL, msg, NULL);
996 msg = skip_blank_lines(msg);
997 c->body_off = msg - start;
999 c->commit_message_parsed = 1;
1002 static void strbuf_wrap(struct strbuf *sb, size_t pos,
1003 size_t width, size_t indent1, size_t indent2)
1005 struct strbuf tmp = STRBUF_INIT;
1007 if (pos)
1008 strbuf_add(&tmp, sb->buf, pos);
1009 strbuf_add_wrapped_text(&tmp, sb->buf + pos,
1010 cast_size_t_to_int(indent1),
1011 cast_size_t_to_int(indent2),
1012 cast_size_t_to_int(width));
1013 strbuf_swap(&tmp, sb);
1014 strbuf_release(&tmp);
1017 static void rewrap_message_tail(struct strbuf *sb,
1018 struct format_commit_context *c,
1019 size_t new_width, size_t new_indent1,
1020 size_t new_indent2)
1022 if (c->width == new_width && c->indent1 == new_indent1 &&
1023 c->indent2 == new_indent2)
1024 return;
1025 if (c->wrap_start < sb->len)
1026 strbuf_wrap(sb, c->wrap_start, c->width, c->indent1, c->indent2);
1027 c->wrap_start = sb->len;
1028 c->width = new_width;
1029 c->indent1 = new_indent1;
1030 c->indent2 = new_indent2;
1033 static int format_reflog_person(struct strbuf *sb,
1034 char part,
1035 struct reflog_walk_info *log,
1036 const struct date_mode *dmode)
1038 const char *ident;
1040 if (!log)
1041 return 2;
1043 ident = get_reflog_ident(log);
1044 if (!ident)
1045 return 2;
1047 return format_person_part(sb, part, ident, strlen(ident), dmode);
1050 static size_t parse_color(struct strbuf *sb, /* in UTF-8 */
1051 const char *placeholder,
1052 struct format_commit_context *c)
1054 const char *rest = placeholder;
1055 const char *basic_color = NULL;
1057 if (placeholder[1] == '(') {
1058 const char *begin = placeholder + 2;
1059 const char *end = strchr(begin, ')');
1060 char color[COLOR_MAXLEN];
1062 if (!end)
1063 return 0;
1065 if (skip_prefix(begin, "auto,", &begin)) {
1066 if (!want_color(c->pretty_ctx->color))
1067 return end - placeholder + 1;
1068 } else if (skip_prefix(begin, "always,", &begin)) {
1069 /* nothing to do; we do not respect want_color at all */
1070 } else {
1071 /* the default is the same as "auto" */
1072 if (!want_color(c->pretty_ctx->color))
1073 return end - placeholder + 1;
1076 if (color_parse_mem(begin, end - begin, color) < 0)
1077 die(_("unable to parse --pretty format"));
1078 strbuf_addstr(sb, color);
1079 return end - placeholder + 1;
1083 * We handle things like "%C(red)" above; for historical reasons, there
1084 * are a few colors that can be specified without parentheses (and
1085 * they cannot support things like "auto" or "always" at all).
1087 if (skip_prefix(placeholder + 1, "red", &rest))
1088 basic_color = GIT_COLOR_RED;
1089 else if (skip_prefix(placeholder + 1, "green", &rest))
1090 basic_color = GIT_COLOR_GREEN;
1091 else if (skip_prefix(placeholder + 1, "blue", &rest))
1092 basic_color = GIT_COLOR_BLUE;
1093 else if (skip_prefix(placeholder + 1, "reset", &rest))
1094 basic_color = GIT_COLOR_RESET;
1096 if (basic_color && want_color(c->pretty_ctx->color))
1097 strbuf_addstr(sb, basic_color);
1099 return rest - placeholder;
1102 static size_t parse_padding_placeholder(const char *placeholder,
1103 struct format_commit_context *c)
1105 const char *ch = placeholder;
1106 enum flush_type flush_type;
1107 int to_column = 0;
1109 switch (*ch++) {
1110 case '<':
1111 flush_type = flush_right;
1112 break;
1113 case '>':
1114 if (*ch == '<') {
1115 flush_type = flush_both;
1116 ch++;
1117 } else if (*ch == '>') {
1118 flush_type = flush_left_and_steal;
1119 ch++;
1120 } else
1121 flush_type = flush_left;
1122 break;
1123 default:
1124 return 0;
1127 /* the next value means "wide enough to that column" */
1128 if (*ch == '|') {
1129 to_column = 1;
1130 ch++;
1133 if (*ch == '(') {
1134 const char *start = ch + 1;
1135 const char *end = start + strcspn(start, ",)");
1136 char *next;
1137 int width;
1138 if (!*end || end == start)
1139 return 0;
1140 width = strtol(start, &next, 10);
1143 * We need to limit the amount of padding, or otherwise this
1144 * would allow the user to pad the buffer by arbitrarily many
1145 * bytes and thus cause resource exhaustion.
1147 if (width < -FORMATTING_LIMIT || width > FORMATTING_LIMIT)
1148 return 0;
1150 if (next == start || width == 0)
1151 return 0;
1152 if (width < 0) {
1153 if (to_column)
1154 width += term_columns();
1155 if (width < 0)
1156 return 0;
1158 c->padding = to_column ? -width : width;
1159 c->flush_type = flush_type;
1161 if (*end == ',') {
1162 start = end + 1;
1163 end = strchr(start, ')');
1164 if (!end || end == start)
1165 return 0;
1166 if (starts_with(start, "trunc)"))
1167 c->truncate = trunc_right;
1168 else if (starts_with(start, "ltrunc)"))
1169 c->truncate = trunc_left;
1170 else if (starts_with(start, "mtrunc)"))
1171 c->truncate = trunc_middle;
1172 else
1173 return 0;
1174 } else
1175 c->truncate = trunc_none;
1177 return end - placeholder + 1;
1179 return 0;
1182 static int match_placeholder_arg_value(const char *to_parse, const char *candidate,
1183 const char **end, const char **valuestart,
1184 size_t *valuelen)
1186 const char *p;
1188 if (!(skip_prefix(to_parse, candidate, &p)))
1189 return 0;
1190 if (valuestart) {
1191 if (*p == '=') {
1192 *valuestart = p + 1;
1193 *valuelen = strcspn(*valuestart, ",)");
1194 p = *valuestart + *valuelen;
1195 } else {
1196 if (*p != ',' && *p != ')')
1197 return 0;
1198 *valuestart = NULL;
1199 *valuelen = 0;
1202 if (*p == ',') {
1203 *end = p + 1;
1204 return 1;
1206 if (*p == ')') {
1207 *end = p;
1208 return 1;
1210 return 0;
1213 static int match_placeholder_bool_arg(const char *to_parse, const char *candidate,
1214 const char **end, int *val)
1216 const char *argval;
1217 char *strval;
1218 size_t arglen;
1219 int v;
1221 if (!match_placeholder_arg_value(to_parse, candidate, end, &argval, &arglen))
1222 return 0;
1224 if (!argval) {
1225 *val = 1;
1226 return 1;
1229 strval = xstrndup(argval, arglen);
1230 v = git_parse_maybe_bool(strval);
1231 free(strval);
1233 if (v == -1)
1234 return 0;
1236 *val = v;
1238 return 1;
1241 static int format_trailer_match_cb(const struct strbuf *key, void *ud)
1243 const struct string_list *list = ud;
1244 const struct string_list_item *item;
1246 for_each_string_list_item (item, list) {
1247 if (key->len == (uintptr_t)item->util &&
1248 !strncasecmp(item->string, key->buf, key->len))
1249 return 1;
1251 return 0;
1254 static struct strbuf *expand_separator(struct strbuf *sb,
1255 const char *argval, size_t arglen)
1257 char *fmt = xstrndup(argval, arglen);
1258 const char *format = fmt;
1260 strbuf_reset(sb);
1261 while (strbuf_expand_step(sb, &format)) {
1262 size_t len;
1264 if (skip_prefix(format, "%", &format))
1265 strbuf_addch(sb, '%');
1266 else if ((len = strbuf_expand_literal(sb, format)))
1267 format += len;
1268 else
1269 strbuf_addch(sb, '%');
1271 free(fmt);
1272 return sb;
1275 int format_set_trailers_options(struct process_trailer_options *opts,
1276 struct string_list *filter_list,
1277 struct strbuf *sepbuf,
1278 struct strbuf *kvsepbuf,
1279 const char **arg,
1280 char **invalid_arg)
1282 for (;;) {
1283 const char *argval;
1284 size_t arglen;
1286 if (**arg == ')')
1287 break;
1289 if (match_placeholder_arg_value(*arg, "key", arg, &argval, &arglen)) {
1290 uintptr_t len = arglen;
1292 if (!argval)
1293 return -1;
1295 if (len && argval[len - 1] == ':')
1296 len--;
1297 string_list_append(filter_list, argval)->util = (char *)len;
1299 opts->filter = format_trailer_match_cb;
1300 opts->filter_data = filter_list;
1301 opts->only_trailers = 1;
1302 } else if (match_placeholder_arg_value(*arg, "separator", arg, &argval, &arglen)) {
1303 opts->separator = expand_separator(sepbuf, argval, arglen);
1304 } else if (match_placeholder_arg_value(*arg, "key_value_separator", arg, &argval, &arglen)) {
1305 opts->key_value_separator = expand_separator(kvsepbuf, argval, arglen);
1306 } else if (!match_placeholder_bool_arg(*arg, "only", arg, &opts->only_trailers) &&
1307 !match_placeholder_bool_arg(*arg, "unfold", arg, &opts->unfold) &&
1308 !match_placeholder_bool_arg(*arg, "keyonly", arg, &opts->key_only) &&
1309 !match_placeholder_bool_arg(*arg, "valueonly", arg, &opts->value_only)) {
1310 if (invalid_arg) {
1311 size_t len = strcspn(*arg, ",)");
1312 *invalid_arg = xstrndup(*arg, len);
1314 return -1;
1317 return 0;
1320 static size_t parse_describe_args(const char *start, struct strvec *args)
1322 struct {
1323 char *name;
1324 enum {
1325 DESCRIBE_ARG_BOOL,
1326 DESCRIBE_ARG_INTEGER,
1327 DESCRIBE_ARG_STRING,
1328 } type;
1329 } option[] = {
1330 { "tags", DESCRIBE_ARG_BOOL},
1331 { "abbrev", DESCRIBE_ARG_INTEGER },
1332 { "exclude", DESCRIBE_ARG_STRING },
1333 { "match", DESCRIBE_ARG_STRING },
1335 const char *arg = start;
1337 for (;;) {
1338 int found = 0;
1339 const char *argval;
1340 size_t arglen = 0;
1341 int optval = 0;
1342 int i;
1344 for (i = 0; !found && i < ARRAY_SIZE(option); i++) {
1345 switch (option[i].type) {
1346 case DESCRIBE_ARG_BOOL:
1347 if (match_placeholder_bool_arg(arg, option[i].name, &arg, &optval)) {
1348 if (optval)
1349 strvec_pushf(args, "--%s", option[i].name);
1350 else
1351 strvec_pushf(args, "--no-%s", option[i].name);
1352 found = 1;
1354 break;
1355 case DESCRIBE_ARG_INTEGER:
1356 if (match_placeholder_arg_value(arg, option[i].name, &arg,
1357 &argval, &arglen)) {
1358 char *endptr;
1359 if (!arglen)
1360 return 0;
1361 strtol(argval, &endptr, 10);
1362 if (endptr - argval != arglen)
1363 return 0;
1364 strvec_pushf(args, "--%s=%.*s", option[i].name, (int)arglen, argval);
1365 found = 1;
1367 break;
1368 case DESCRIBE_ARG_STRING:
1369 if (match_placeholder_arg_value(arg, option[i].name, &arg,
1370 &argval, &arglen)) {
1371 if (!arglen)
1372 return 0;
1373 strvec_pushf(args, "--%s=%.*s", option[i].name, (int)arglen, argval);
1374 found = 1;
1376 break;
1379 if (!found)
1380 break;
1383 return arg - start;
1386 static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
1387 const char *placeholder,
1388 void *context)
1390 struct format_commit_context *c = context;
1391 const struct commit *commit = c->commit;
1392 const char *msg = c->message;
1393 struct commit_list *p;
1394 const char *arg, *eol;
1395 size_t res;
1396 char **slot;
1398 /* these are independent of the commit */
1399 res = strbuf_expand_literal(sb, placeholder);
1400 if (res)
1401 return res;
1403 switch (placeholder[0]) {
1404 case 'C':
1405 if (starts_with(placeholder + 1, "(auto)")) {
1406 c->auto_color = want_color(c->pretty_ctx->color);
1407 if (c->auto_color && sb->len)
1408 strbuf_addstr(sb, GIT_COLOR_RESET);
1409 return 7; /* consumed 7 bytes, "C(auto)" */
1410 } else {
1411 int ret = parse_color(sb, placeholder, c);
1412 if (ret)
1413 c->auto_color = 0;
1415 * Otherwise, we decided to treat %C<unknown>
1416 * as a literal string, and the previous
1417 * %C(auto) is still valid.
1419 return ret;
1421 case 'w':
1422 if (placeholder[1] == '(') {
1423 unsigned long width = 0, indent1 = 0, indent2 = 0;
1424 char *next;
1425 const char *start = placeholder + 2;
1426 const char *end = strchr(start, ')');
1427 if (!end)
1428 return 0;
1429 if (end > start) {
1430 width = strtoul(start, &next, 10);
1431 if (*next == ',') {
1432 indent1 = strtoul(next + 1, &next, 10);
1433 if (*next == ',') {
1434 indent2 = strtoul(next + 1,
1435 &next, 10);
1438 if (*next != ')')
1439 return 0;
1443 * We need to limit the format here as it allows the
1444 * user to prepend arbitrarily many bytes to the buffer
1445 * when rewrapping.
1447 if (width > FORMATTING_LIMIT ||
1448 indent1 > FORMATTING_LIMIT ||
1449 indent2 > FORMATTING_LIMIT)
1450 return 0;
1451 rewrap_message_tail(sb, c, width, indent1, indent2);
1452 return end - placeholder + 1;
1453 } else
1454 return 0;
1456 case '<':
1457 case '>':
1458 return parse_padding_placeholder(placeholder, c);
1461 if (skip_prefix(placeholder, "(describe", &arg)) {
1462 struct child_process cmd = CHILD_PROCESS_INIT;
1463 struct strbuf out = STRBUF_INIT;
1464 struct strbuf err = STRBUF_INIT;
1465 struct pretty_print_describe_status *describe_status;
1467 describe_status = c->pretty_ctx->describe_status;
1468 if (describe_status) {
1469 if (!describe_status->max_invocations)
1470 return 0;
1471 describe_status->max_invocations--;
1474 cmd.git_cmd = 1;
1475 strvec_push(&cmd.args, "describe");
1477 if (*arg == ':') {
1478 arg++;
1479 arg += parse_describe_args(arg, &cmd.args);
1482 if (*arg != ')') {
1483 child_process_clear(&cmd);
1484 return 0;
1487 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1488 pipe_command(&cmd, NULL, 0, &out, 0, &err, 0);
1489 strbuf_rtrim(&out);
1490 strbuf_addbuf(sb, &out);
1491 strbuf_release(&out);
1492 strbuf_release(&err);
1493 return arg - placeholder + 1;
1496 /* these depend on the commit */
1497 if (!commit->object.parsed)
1498 parse_object(the_repository, &commit->object.oid);
1500 switch (placeholder[0]) {
1501 case 'H': /* commit hash */
1502 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1503 strbuf_addstr(sb, oid_to_hex(&commit->object.oid));
1504 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1505 return 1;
1506 case 'h': /* abbreviated commit hash */
1507 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1508 strbuf_add_unique_abbrev(sb, &commit->object.oid,
1509 c->pretty_ctx->abbrev);
1510 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1511 return 1;
1512 case 'T': /* tree hash */
1513 strbuf_addstr(sb, oid_to_hex(get_commit_tree_oid(commit)));
1514 return 1;
1515 case 't': /* abbreviated tree hash */
1516 strbuf_add_unique_abbrev(sb,
1517 get_commit_tree_oid(commit),
1518 c->pretty_ctx->abbrev);
1519 return 1;
1520 case 'P': /* parent hashes */
1521 for (p = commit->parents; p; p = p->next) {
1522 if (p != commit->parents)
1523 strbuf_addch(sb, ' ');
1524 strbuf_addstr(sb, oid_to_hex(&p->item->object.oid));
1526 return 1;
1527 case 'p': /* abbreviated parent hashes */
1528 for (p = commit->parents; p; p = p->next) {
1529 if (p != commit->parents)
1530 strbuf_addch(sb, ' ');
1531 strbuf_add_unique_abbrev(sb, &p->item->object.oid,
1532 c->pretty_ctx->abbrev);
1534 return 1;
1535 case 'm': /* left/right/bottom */
1536 strbuf_addstr(sb, get_revision_mark(NULL, commit));
1537 return 1;
1538 case 'd':
1539 format_decorations(sb, commit, c->auto_color);
1540 return 1;
1541 case 'D':
1542 format_decorations_extended(sb, commit, c->auto_color, "", ", ", "");
1543 return 1;
1544 case 'S': /* tag/branch like --source */
1545 if (!(c->pretty_ctx->rev && c->pretty_ctx->rev->sources))
1546 return 0;
1547 slot = revision_sources_at(c->pretty_ctx->rev->sources, commit);
1548 if (!(slot && *slot))
1549 return 0;
1550 strbuf_addstr(sb, *slot);
1551 return 1;
1552 case 'g': /* reflog info */
1553 switch(placeholder[1]) {
1554 case 'd': /* reflog selector */
1555 case 'D':
1556 if (c->pretty_ctx->reflog_info)
1557 get_reflog_selector(sb,
1558 c->pretty_ctx->reflog_info,
1559 &c->pretty_ctx->date_mode,
1560 c->pretty_ctx->date_mode_explicit,
1561 (placeholder[1] == 'd'));
1562 return 2;
1563 case 's': /* reflog message */
1564 if (c->pretty_ctx->reflog_info)
1565 get_reflog_message(sb, c->pretty_ctx->reflog_info);
1566 return 2;
1567 case 'n':
1568 case 'N':
1569 case 'e':
1570 case 'E':
1571 return format_reflog_person(sb,
1572 placeholder[1],
1573 c->pretty_ctx->reflog_info,
1574 &c->pretty_ctx->date_mode);
1576 return 0; /* unknown %g placeholder */
1577 case 'N':
1578 if (c->pretty_ctx->notes_message) {
1579 strbuf_addstr(sb, c->pretty_ctx->notes_message);
1580 return 1;
1582 return 0;
1585 if (placeholder[0] == 'G') {
1586 if (!c->signature_check.result)
1587 check_commit_signature(c->commit, &(c->signature_check));
1588 switch (placeholder[1]) {
1589 case 'G':
1590 if (c->signature_check.output)
1591 strbuf_addstr(sb, c->signature_check.output);
1592 break;
1593 case '?':
1594 switch (c->signature_check.result) {
1595 case 'G':
1596 switch (c->signature_check.trust_level) {
1597 case TRUST_UNDEFINED:
1598 case TRUST_NEVER:
1599 strbuf_addch(sb, 'U');
1600 break;
1601 default:
1602 strbuf_addch(sb, 'G');
1603 break;
1605 break;
1606 case 'B':
1607 case 'E':
1608 case 'N':
1609 case 'X':
1610 case 'Y':
1611 case 'R':
1612 strbuf_addch(sb, c->signature_check.result);
1614 break;
1615 case 'S':
1616 if (c->signature_check.signer)
1617 strbuf_addstr(sb, c->signature_check.signer);
1618 break;
1619 case 'K':
1620 if (c->signature_check.key)
1621 strbuf_addstr(sb, c->signature_check.key);
1622 break;
1623 case 'F':
1624 if (c->signature_check.fingerprint)
1625 strbuf_addstr(sb, c->signature_check.fingerprint);
1626 break;
1627 case 'P':
1628 if (c->signature_check.primary_key_fingerprint)
1629 strbuf_addstr(sb, c->signature_check.primary_key_fingerprint);
1630 break;
1631 case 'T':
1632 strbuf_addstr(sb, gpg_trust_level_to_str(c->signature_check.trust_level));
1633 break;
1634 default:
1635 return 0;
1637 return 2;
1640 /* For the rest we have to parse the commit header. */
1641 if (!c->commit_header_parsed) {
1642 msg = c->message =
1643 repo_logmsg_reencode(c->repository, commit,
1644 &c->commit_encoding, "UTF-8");
1645 parse_commit_header(c);
1648 switch (placeholder[0]) {
1649 case 'a': /* author ... */
1650 return format_person_part(sb, placeholder[1],
1651 msg + c->author.off, c->author.len,
1652 &c->pretty_ctx->date_mode);
1653 case 'c': /* committer ... */
1654 return format_person_part(sb, placeholder[1],
1655 msg + c->committer.off, c->committer.len,
1656 &c->pretty_ctx->date_mode);
1657 case 'e': /* encoding */
1658 if (c->commit_encoding)
1659 strbuf_addstr(sb, c->commit_encoding);
1660 return 1;
1661 case 'B': /* raw body */
1662 /* message_off is always left at the initial newline */
1663 strbuf_addstr(sb, msg + c->message_off + 1);
1664 return 1;
1667 /* Now we need to parse the commit message. */
1668 if (!c->commit_message_parsed)
1669 parse_commit_message(c);
1671 switch (placeholder[0]) {
1672 case 's': /* subject */
1673 format_subject(sb, msg + c->subject_off, " ");
1674 return 1;
1675 case 'f': /* sanitized subject */
1676 eol = strchrnul(msg + c->subject_off, '\n');
1677 format_sanitized_subject(sb, msg + c->subject_off, eol - (msg + c->subject_off));
1678 return 1;
1679 case 'b': /* body */
1680 strbuf_addstr(sb, msg + c->body_off);
1681 return 1;
1684 if (skip_prefix(placeholder, "(trailers", &arg)) {
1685 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1686 struct string_list filter_list = STRING_LIST_INIT_NODUP;
1687 struct strbuf sepbuf = STRBUF_INIT;
1688 struct strbuf kvsepbuf = STRBUF_INIT;
1689 size_t ret = 0;
1691 opts.no_divider = 1;
1693 if (*arg == ':') {
1694 arg++;
1695 if (format_set_trailers_options(&opts, &filter_list, &sepbuf, &kvsepbuf, &arg, NULL))
1696 goto trailer_out;
1698 if (*arg == ')') {
1699 format_trailers_from_commit(sb, msg + c->subject_off, &opts);
1700 ret = arg - placeholder + 1;
1702 trailer_out:
1703 string_list_clear(&filter_list, 0);
1704 strbuf_release(&sepbuf);
1705 return ret;
1708 return 0; /* unknown placeholder */
1711 static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */
1712 const char *placeholder,
1713 struct format_commit_context *c)
1715 struct strbuf local_sb = STRBUF_INIT;
1716 size_t total_consumed = 0;
1717 int len, padding = c->padding;
1719 if (padding < 0) {
1720 const char *start = strrchr(sb->buf, '\n');
1721 int occupied;
1722 if (!start)
1723 start = sb->buf;
1724 occupied = utf8_strnwidth(start, strlen(start), 1);
1725 occupied += c->pretty_ctx->graph_width;
1726 padding = (-padding) - occupied;
1728 while (1) {
1729 int modifier = *placeholder == 'C';
1730 size_t consumed = format_commit_one(&local_sb, placeholder, c);
1731 total_consumed += consumed;
1733 if (!modifier)
1734 break;
1736 placeholder += consumed;
1737 if (*placeholder != '%')
1738 break;
1739 placeholder++;
1740 total_consumed++;
1742 len = utf8_strnwidth(local_sb.buf, local_sb.len, 1);
1744 if (c->flush_type == flush_left_and_steal) {
1745 const char *ch = sb->buf + sb->len - 1;
1746 while (len > padding && ch > sb->buf) {
1747 const char *p;
1748 if (*ch == ' ') {
1749 ch--;
1750 padding++;
1751 continue;
1753 /* check for trailing ansi sequences */
1754 if (*ch != 'm')
1755 break;
1756 p = ch - 1;
1757 while (p > sb->buf && ch - p < 10 && *p != '\033')
1758 p--;
1759 if (*p != '\033' ||
1760 ch + 1 - p != display_mode_esc_sequence_len(p))
1761 break;
1763 * got a good ansi sequence, put it back to
1764 * local_sb as we're cutting sb
1766 strbuf_insert(&local_sb, 0, p, ch + 1 - p);
1767 ch = p - 1;
1769 strbuf_setlen(sb, ch + 1 - sb->buf);
1770 c->flush_type = flush_left;
1773 if (len > padding) {
1774 switch (c->truncate) {
1775 case trunc_left:
1776 strbuf_utf8_replace(&local_sb,
1777 0, len - (padding - 2),
1778 "..");
1779 break;
1780 case trunc_middle:
1781 strbuf_utf8_replace(&local_sb,
1782 padding / 2 - 1,
1783 len - (padding - 2),
1784 "..");
1785 break;
1786 case trunc_right:
1787 strbuf_utf8_replace(&local_sb,
1788 padding - 2, len - (padding - 2),
1789 "..");
1790 break;
1791 case trunc_none:
1792 break;
1794 strbuf_addbuf(sb, &local_sb);
1795 } else {
1796 size_t sb_len = sb->len, offset = 0;
1797 if (c->flush_type == flush_left)
1798 offset = padding - len;
1799 else if (c->flush_type == flush_both)
1800 offset = (padding - len) / 2;
1802 * we calculate padding in columns, now
1803 * convert it back to chars
1805 padding = padding - len + local_sb.len;
1806 strbuf_addchars(sb, ' ', padding);
1807 memcpy(sb->buf + sb_len + offset, local_sb.buf,
1808 local_sb.len);
1810 strbuf_release(&local_sb);
1811 c->flush_type = no_flush;
1812 return total_consumed;
1815 static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */
1816 const char *placeholder,
1817 struct format_commit_context *context)
1819 size_t consumed, orig_len;
1820 enum {
1821 NO_MAGIC,
1822 ADD_LF_BEFORE_NON_EMPTY,
1823 DEL_LF_BEFORE_EMPTY,
1824 ADD_SP_BEFORE_NON_EMPTY
1825 } magic = NO_MAGIC;
1827 switch (placeholder[0]) {
1828 case '-':
1829 magic = DEL_LF_BEFORE_EMPTY;
1830 break;
1831 case '+':
1832 magic = ADD_LF_BEFORE_NON_EMPTY;
1833 break;
1834 case ' ':
1835 magic = ADD_SP_BEFORE_NON_EMPTY;
1836 break;
1837 default:
1838 break;
1840 if (magic != NO_MAGIC) {
1841 placeholder++;
1843 switch (placeholder[0]) {
1844 case 'w':
1846 * `%+w()` cannot ever expand to a non-empty string,
1847 * and it potentially changes the layout of preceding
1848 * contents. We're thus not able to handle the magic in
1849 * this combination and refuse the pattern.
1851 return 0;
1855 orig_len = sb->len;
1856 if ((context)->flush_type != no_flush)
1857 consumed = format_and_pad_commit(sb, placeholder, context);
1858 else
1859 consumed = format_commit_one(sb, placeholder, context);
1860 if (magic == NO_MAGIC)
1861 return consumed;
1863 if ((orig_len == sb->len) && magic == DEL_LF_BEFORE_EMPTY) {
1864 while (sb->len && sb->buf[sb->len - 1] == '\n')
1865 strbuf_setlen(sb, sb->len - 1);
1866 } else if (orig_len != sb->len) {
1867 if (magic == ADD_LF_BEFORE_NON_EMPTY)
1868 strbuf_insertstr(sb, orig_len, "\n");
1869 else if (magic == ADD_SP_BEFORE_NON_EMPTY)
1870 strbuf_insertstr(sb, orig_len, " ");
1872 return consumed + 1;
1875 void userformat_find_requirements(const char *fmt, struct userformat_want *w)
1877 struct strbuf dummy = STRBUF_INIT;
1879 if (!fmt) {
1880 if (!user_format)
1881 return;
1882 fmt = user_format;
1884 while (strbuf_expand_step(&dummy, &fmt)) {
1885 if (skip_prefix(fmt, "%", &fmt))
1886 continue;
1888 if (*fmt == '+' || *fmt == '-' || *fmt == ' ')
1889 fmt++;
1891 switch (*fmt) {
1892 case 'N':
1893 w->notes = 1;
1894 break;
1895 case 'S':
1896 w->source = 1;
1897 break;
1898 case 'd':
1899 case 'D':
1900 w->decorate = 1;
1901 break;
1904 strbuf_release(&dummy);
1907 void repo_format_commit_message(struct repository *r,
1908 const struct commit *commit,
1909 const char *format, struct strbuf *sb,
1910 const struct pretty_print_context *pretty_ctx)
1912 struct format_commit_context context = {
1913 .repository = r,
1914 .commit = commit,
1915 .pretty_ctx = pretty_ctx,
1916 .wrap_start = sb->len
1918 const char *output_enc = pretty_ctx->output_encoding;
1919 const char *utf8 = "UTF-8";
1921 while (strbuf_expand_step(sb, &format)) {
1922 size_t len;
1924 if (skip_prefix(format, "%", &format))
1925 strbuf_addch(sb, '%');
1926 else if ((len = format_commit_item(sb, format, &context)))
1927 format += len;
1928 else
1929 strbuf_addch(sb, '%');
1931 rewrap_message_tail(sb, &context, 0, 0, 0);
1934 * Convert output to an actual output encoding; note that
1935 * format_commit_item() will always use UTF-8, so we don't
1936 * have to bother if that's what the output wants.
1938 if (output_enc) {
1939 if (same_encoding(utf8, output_enc))
1940 output_enc = NULL;
1941 } else {
1942 if (context.commit_encoding &&
1943 !same_encoding(context.commit_encoding, utf8))
1944 output_enc = context.commit_encoding;
1947 if (output_enc) {
1948 size_t outsz;
1949 char *out = reencode_string_len(sb->buf, sb->len,
1950 output_enc, utf8, &outsz);
1951 if (out)
1952 strbuf_attach(sb, out, outsz, outsz + 1);
1955 free(context.commit_encoding);
1956 repo_unuse_commit_buffer(r, commit, context.message);
1959 static void pp_header(struct pretty_print_context *pp,
1960 const char *encoding,
1961 const struct commit *commit,
1962 const char **msg_p,
1963 struct strbuf *sb)
1965 int parents_shown = 0;
1967 for (;;) {
1968 const char *name, *line = *msg_p;
1969 int linelen = get_one_line(*msg_p);
1971 if (!linelen)
1972 return;
1973 *msg_p += linelen;
1975 if (linelen == 1)
1976 /* End of header */
1977 return;
1979 if (pp->fmt == CMIT_FMT_RAW) {
1980 strbuf_add(sb, line, linelen);
1981 continue;
1984 if (starts_with(line, "parent ")) {
1985 if (linelen != the_hash_algo->hexsz + 8)
1986 die("bad parent line in commit");
1987 continue;
1990 if (!parents_shown) {
1991 unsigned num = commit_list_count(commit->parents);
1992 /* with enough slop */
1993 strbuf_grow(sb, num * (GIT_MAX_HEXSZ + 10) + 20);
1994 add_merge_info(pp, sb, commit);
1995 parents_shown = 1;
1999 * MEDIUM == DEFAULT shows only author with dates.
2000 * FULL shows both authors but not dates.
2001 * FULLER shows both authors and dates.
2003 if (skip_prefix(line, "author ", &name)) {
2004 strbuf_grow(sb, linelen + 80);
2005 pp_user_info(pp, "Author", sb, name, encoding);
2007 if (skip_prefix(line, "committer ", &name) &&
2008 (pp->fmt == CMIT_FMT_FULL || pp->fmt == CMIT_FMT_FULLER)) {
2009 strbuf_grow(sb, linelen + 80);
2010 pp_user_info(pp, "Commit", sb, name, encoding);
2015 void pp_title_line(struct pretty_print_context *pp,
2016 const char **msg_p,
2017 struct strbuf *sb,
2018 const char *encoding,
2019 int need_8bit_cte)
2021 static const int max_length = 78; /* per rfc2047 */
2022 struct strbuf title;
2024 strbuf_init(&title, 80);
2025 *msg_p = format_subject(&title, *msg_p,
2026 pp->preserve_subject ? "\n" : " ");
2028 strbuf_grow(sb, title.len + 1024);
2029 if (pp->print_email_subject) {
2030 if (pp->rev)
2031 fmt_output_email_subject(sb, pp->rev);
2032 if (pp->encode_email_headers &&
2033 needs_rfc2047_encoding(title.buf, title.len))
2034 add_rfc2047(sb, title.buf, title.len,
2035 encoding, RFC2047_SUBJECT);
2036 else
2037 strbuf_add_wrapped_bytes(sb, title.buf, title.len,
2038 -last_line_length(sb), 1, max_length);
2039 } else {
2040 strbuf_addbuf(sb, &title);
2042 strbuf_addch(sb, '\n');
2044 if (need_8bit_cte == 0) {
2045 int i;
2046 for (i = 0; i < pp->in_body_headers.nr; i++) {
2047 if (has_non_ascii(pp->in_body_headers.items[i].string)) {
2048 need_8bit_cte = 1;
2049 break;
2054 if (need_8bit_cte > 0) {
2055 const char *header_fmt =
2056 "MIME-Version: 1.0\n"
2057 "Content-Type: text/plain; charset=%s\n"
2058 "Content-Transfer-Encoding: 8bit\n";
2059 strbuf_addf(sb, header_fmt, encoding);
2061 if (pp->after_subject) {
2062 strbuf_addstr(sb, pp->after_subject);
2064 if (cmit_fmt_is_mail(pp->fmt)) {
2065 strbuf_addch(sb, '\n');
2068 if (pp->in_body_headers.nr) {
2069 int i;
2070 for (i = 0; i < pp->in_body_headers.nr; i++) {
2071 strbuf_addstr(sb, pp->in_body_headers.items[i].string);
2072 free(pp->in_body_headers.items[i].string);
2074 string_list_clear(&pp->in_body_headers, 0);
2075 strbuf_addch(sb, '\n');
2078 strbuf_release(&title);
2081 static int pp_utf8_width(const char *start, const char *end)
2083 int width = 0;
2084 size_t remain = end - start;
2086 while (remain) {
2087 int n = utf8_width(&start, &remain);
2088 if (n < 0 || !start)
2089 return -1;
2090 width += n;
2092 return width;
2095 static void strbuf_add_tabexpand(struct strbuf *sb, struct grep_opt *opt,
2096 int color, int tabwidth, const char *line,
2097 int linelen)
2099 const char *tab;
2101 while ((tab = memchr(line, '\t', linelen)) != NULL) {
2102 int width = pp_utf8_width(line, tab);
2105 * If it wasn't well-formed utf8, or it
2106 * had characters with badly defined
2107 * width (control characters etc), just
2108 * give up on trying to align things.
2110 if (width < 0)
2111 break;
2113 /* Output the data .. */
2114 append_line_with_color(sb, opt, line, tab - line, color,
2115 GREP_CONTEXT_BODY,
2116 GREP_HEADER_FIELD_MAX);
2118 /* .. and the de-tabified tab */
2119 strbuf_addchars(sb, ' ', tabwidth - (width % tabwidth));
2121 /* Skip over the printed part .. */
2122 linelen -= tab + 1 - line;
2123 line = tab + 1;
2127 * Print out everything after the last tab without
2128 * worrying about width - there's nothing more to
2129 * align.
2131 append_line_with_color(sb, opt, line, linelen, color, GREP_CONTEXT_BODY,
2132 GREP_HEADER_FIELD_MAX);
2136 * pp_handle_indent() prints out the intendation, and
2137 * the whole line (without the final newline), after
2138 * de-tabifying.
2140 static void pp_handle_indent(struct pretty_print_context *pp,
2141 struct strbuf *sb, int indent,
2142 const char *line, int linelen)
2144 struct grep_opt *opt = pp->rev ? &pp->rev->grep_filter : NULL;
2146 strbuf_addchars(sb, ' ', indent);
2147 if (pp->expand_tabs_in_log)
2148 strbuf_add_tabexpand(sb, opt, pp->color, pp->expand_tabs_in_log,
2149 line, linelen);
2150 else
2151 append_line_with_color(sb, opt, line, linelen, pp->color,
2152 GREP_CONTEXT_BODY,
2153 GREP_HEADER_FIELD_MAX);
2156 static int is_mboxrd_from(const char *line, int len)
2159 * a line matching /^From $/ here would only have len == 4
2160 * at this point because is_empty_line would've trimmed all
2161 * trailing space
2163 return len > 4 && starts_with(line + strspn(line, ">"), "From ");
2166 void pp_remainder(struct pretty_print_context *pp,
2167 const char **msg_p,
2168 struct strbuf *sb,
2169 int indent)
2171 struct grep_opt *opt = pp->rev ? &pp->rev->grep_filter : NULL;
2172 int first = 1;
2174 for (;;) {
2175 const char *line = *msg_p;
2176 int linelen = get_one_line(line);
2177 *msg_p += linelen;
2179 if (!linelen)
2180 break;
2182 if (is_blank_line(line, &linelen)) {
2183 if (first)
2184 continue;
2185 if (pp->fmt == CMIT_FMT_SHORT)
2186 break;
2188 first = 0;
2190 strbuf_grow(sb, linelen + indent + 20);
2191 if (indent)
2192 pp_handle_indent(pp, sb, indent, line, linelen);
2193 else if (pp->expand_tabs_in_log)
2194 strbuf_add_tabexpand(sb, opt, pp->color,
2195 pp->expand_tabs_in_log, line,
2196 linelen);
2197 else {
2198 if (pp->fmt == CMIT_FMT_MBOXRD &&
2199 is_mboxrd_from(line, linelen))
2200 strbuf_addch(sb, '>');
2202 append_line_with_color(sb, opt, line, linelen,
2203 pp->color, GREP_CONTEXT_BODY,
2204 GREP_HEADER_FIELD_MAX);
2206 strbuf_addch(sb, '\n');
2210 void pretty_print_commit(struct pretty_print_context *pp,
2211 const struct commit *commit,
2212 struct strbuf *sb)
2214 unsigned long beginning_of_body;
2215 int indent = 4;
2216 const char *msg;
2217 const char *reencoded;
2218 const char *encoding;
2219 int need_8bit_cte = pp->need_8bit_cte;
2221 if (pp->fmt == CMIT_FMT_USERFORMAT) {
2222 repo_format_commit_message(the_repository, commit,
2223 user_format, sb, pp);
2224 return;
2227 encoding = get_log_output_encoding();
2228 msg = reencoded = repo_logmsg_reencode(the_repository, commit, NULL,
2229 encoding);
2231 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
2232 indent = 0;
2235 * We need to check and emit Content-type: to mark it
2236 * as 8-bit if we haven't done so.
2238 if (cmit_fmt_is_mail(pp->fmt) && need_8bit_cte == 0) {
2239 int i, ch, in_body;
2241 for (in_body = i = 0; (ch = msg[i]); i++) {
2242 if (!in_body) {
2243 /* author could be non 7-bit ASCII but
2244 * the log may be so; skip over the
2245 * header part first.
2247 if (ch == '\n' && msg[i+1] == '\n')
2248 in_body = 1;
2250 else if (non_ascii(ch)) {
2251 need_8bit_cte = 1;
2252 break;
2257 pp_header(pp, encoding, commit, &msg, sb);
2258 if (pp->fmt != CMIT_FMT_ONELINE && !pp->print_email_subject) {
2259 strbuf_addch(sb, '\n');
2262 /* Skip excess blank lines at the beginning of body, if any... */
2263 msg = skip_blank_lines(msg);
2265 /* These formats treat the title line specially. */
2266 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
2267 pp_title_line(pp, &msg, sb, encoding, need_8bit_cte);
2269 beginning_of_body = sb->len;
2270 if (pp->fmt != CMIT_FMT_ONELINE)
2271 pp_remainder(pp, &msg, sb, indent);
2272 strbuf_rtrim(sb);
2274 /* Make sure there is an EOLN for the non-oneline case */
2275 if (pp->fmt != CMIT_FMT_ONELINE)
2276 strbuf_addch(sb, '\n');
2279 * The caller may append additional body text in e-mail
2280 * format. Make sure we did not strip the blank line
2281 * between the header and the body.
2283 if (cmit_fmt_is_mail(pp->fmt) && sb->len <= beginning_of_body)
2284 strbuf_addch(sb, '\n');
2286 repo_unuse_commit_buffer(the_repository, commit, reencoded);
2289 void pp_commit_easy(enum cmit_fmt fmt, const struct commit *commit,
2290 struct strbuf *sb)
2292 struct pretty_print_context pp = {0};
2293 pp.fmt = fmt;
2294 pretty_print_commit(&pp, commit, sb);