t2400: drop no-op `--sq` from rev-parse call
[git.git] / pretty.c
blob76fc4f61e40d8ac6c30b054cf6e2558aa403d96f
1 #include "cache.h"
2 #include "alloc.h"
3 #include "config.h"
4 #include "commit.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "utf8.h"
9 #include "diff.h"
10 #include "revision.h"
11 #include "string-list.h"
12 #include "mailmap.h"
13 #include "log-tree.h"
14 #include "notes.h"
15 #include "color.h"
16 #include "reflog-walk.h"
17 #include "gpg-interface.h"
18 #include "trailer.h"
19 #include "run-command.h"
22 * The limit for formatting directives, which enable the caller to append
23 * arbitrarily many bytes to the formatted buffer. This includes padding
24 * and wrapping formatters.
26 #define FORMATTING_LIMIT (16 * 1024)
28 static char *user_format;
29 static struct cmt_fmt_map {
30 const char *name;
31 enum cmit_fmt format;
32 int is_tformat;
33 int expand_tabs_in_log;
34 int is_alias;
35 enum date_mode_type default_date_mode_type;
36 const char *user_format;
37 } *commit_formats;
38 static size_t builtin_formats_len;
39 static size_t commit_formats_len;
40 static size_t commit_formats_alloc;
41 static struct cmt_fmt_map *find_commit_format(const char *sought);
43 int commit_format_is_empty(enum cmit_fmt fmt)
45 return fmt == CMIT_FMT_USERFORMAT && !*user_format;
48 static void save_user_format(struct rev_info *rev, const char *cp, int is_tformat)
50 free(user_format);
51 user_format = xstrdup(cp);
52 if (is_tformat)
53 rev->use_terminator = 1;
54 rev->commit_format = CMIT_FMT_USERFORMAT;
57 static int git_pretty_formats_config(const char *var, const char *value,
58 void *cb UNUSED)
60 struct cmt_fmt_map *commit_format = NULL;
61 const char *name;
62 const char *fmt;
63 int i;
65 if (!skip_prefix(var, "pretty.", &name))
66 return 0;
68 for (i = 0; i < builtin_formats_len; i++) {
69 if (!strcmp(commit_formats[i].name, name))
70 return 0;
73 for (i = builtin_formats_len; i < commit_formats_len; i++) {
74 if (!strcmp(commit_formats[i].name, name)) {
75 commit_format = &commit_formats[i];
76 break;
80 if (!commit_format) {
81 ALLOC_GROW(commit_formats, commit_formats_len+1,
82 commit_formats_alloc);
83 commit_format = &commit_formats[commit_formats_len];
84 memset(commit_format, 0, sizeof(*commit_format));
85 commit_formats_len++;
88 commit_format->name = xstrdup(name);
89 commit_format->format = CMIT_FMT_USERFORMAT;
90 if (git_config_string(&fmt, var, value))
91 return -1;
93 if (skip_prefix(fmt, "format:", &fmt))
94 commit_format->is_tformat = 0;
95 else if (skip_prefix(fmt, "tformat:", &fmt) || strchr(fmt, '%'))
96 commit_format->is_tformat = 1;
97 else
98 commit_format->is_alias = 1;
99 commit_format->user_format = fmt;
101 return 0;
104 static void setup_commit_formats(void)
106 struct cmt_fmt_map builtin_formats[] = {
107 { "raw", CMIT_FMT_RAW, 0, 0 },
108 { "medium", CMIT_FMT_MEDIUM, 0, 8 },
109 { "short", CMIT_FMT_SHORT, 0, 0 },
110 { "email", CMIT_FMT_EMAIL, 0, 0 },
111 { "mboxrd", CMIT_FMT_MBOXRD, 0, 0 },
112 { "fuller", CMIT_FMT_FULLER, 0, 8 },
113 { "full", CMIT_FMT_FULL, 0, 8 },
114 { "oneline", CMIT_FMT_ONELINE, 1, 0 },
115 { "reference", CMIT_FMT_USERFORMAT, 1, 0,
116 0, DATE_SHORT, "%C(auto)%h (%s, %ad)" },
118 * Please update $__git_log_pretty_formats in
119 * git-completion.bash when you add new formats.
122 commit_formats_len = ARRAY_SIZE(builtin_formats);
123 builtin_formats_len = commit_formats_len;
124 ALLOC_GROW(commit_formats, commit_formats_len, commit_formats_alloc);
125 COPY_ARRAY(commit_formats, builtin_formats,
126 ARRAY_SIZE(builtin_formats));
128 git_config(git_pretty_formats_config, NULL);
131 static struct cmt_fmt_map *find_commit_format_recursive(const char *sought,
132 const char *original,
133 int num_redirections)
135 struct cmt_fmt_map *found = NULL;
136 size_t found_match_len = 0;
137 int i;
139 if (num_redirections >= commit_formats_len)
140 die("invalid --pretty format: "
141 "'%s' references an alias which points to itself",
142 original);
144 for (i = 0; i < commit_formats_len; i++) {
145 size_t match_len;
147 if (!starts_with(commit_formats[i].name, sought))
148 continue;
150 match_len = strlen(commit_formats[i].name);
151 if (found == NULL || found_match_len > match_len) {
152 found = &commit_formats[i];
153 found_match_len = match_len;
157 if (found && found->is_alias) {
158 found = find_commit_format_recursive(found->user_format,
159 original,
160 num_redirections+1);
163 return found;
166 static struct cmt_fmt_map *find_commit_format(const char *sought)
168 if (!commit_formats)
169 setup_commit_formats();
171 return find_commit_format_recursive(sought, sought, 0);
174 void get_commit_format(const char *arg, struct rev_info *rev)
176 struct cmt_fmt_map *commit_format;
178 rev->use_terminator = 0;
179 if (!arg) {
180 rev->commit_format = CMIT_FMT_DEFAULT;
181 return;
183 if (skip_prefix(arg, "format:", &arg)) {
184 save_user_format(rev, arg, 0);
185 return;
188 if (!*arg || skip_prefix(arg, "tformat:", &arg) || strchr(arg, '%')) {
189 save_user_format(rev, arg, 1);
190 return;
193 commit_format = find_commit_format(arg);
194 if (!commit_format)
195 die("invalid --pretty format: %s", arg);
197 rev->commit_format = commit_format->format;
198 rev->use_terminator = commit_format->is_tformat;
199 rev->expand_tabs_in_log_default = commit_format->expand_tabs_in_log;
200 if (!rev->date_mode_explicit && commit_format->default_date_mode_type)
201 rev->date_mode.type = commit_format->default_date_mode_type;
202 if (commit_format->format == CMIT_FMT_USERFORMAT) {
203 save_user_format(rev, commit_format->user_format,
204 commit_format->is_tformat);
209 * Generic support for pretty-printing the header
211 static int get_one_line(const char *msg)
213 int ret = 0;
215 for (;;) {
216 char c = *msg++;
217 if (!c)
218 break;
219 ret++;
220 if (c == '\n')
221 break;
223 return ret;
226 /* High bit set, or ISO-2022-INT */
227 static int non_ascii(int ch)
229 return !isascii(ch) || ch == '\033';
232 int has_non_ascii(const char *s)
234 int ch;
235 if (!s)
236 return 0;
237 while ((ch = *s++) != '\0') {
238 if (non_ascii(ch))
239 return 1;
241 return 0;
244 static int is_rfc822_special(char ch)
246 switch (ch) {
247 case '(':
248 case ')':
249 case '<':
250 case '>':
251 case '[':
252 case ']':
253 case ':':
254 case ';':
255 case '@':
256 case ',':
257 case '.':
258 case '"':
259 case '\\':
260 return 1;
261 default:
262 return 0;
266 static int needs_rfc822_quoting(const char *s, int len)
268 int i;
269 for (i = 0; i < len; i++)
270 if (is_rfc822_special(s[i]))
271 return 1;
272 return 0;
275 static int last_line_length(struct strbuf *sb)
277 int i;
279 /* How many bytes are already used on the last line? */
280 for (i = sb->len - 1; i >= 0; i--)
281 if (sb->buf[i] == '\n')
282 break;
283 return sb->len - (i + 1);
286 static void add_rfc822_quoted(struct strbuf *out, const char *s, int len)
288 int i;
290 /* just a guess, we may have to also backslash-quote */
291 strbuf_grow(out, len + 2);
293 strbuf_addch(out, '"');
294 for (i = 0; i < len; i++) {
295 switch (s[i]) {
296 case '"':
297 case '\\':
298 strbuf_addch(out, '\\');
299 /* fall through */
300 default:
301 strbuf_addch(out, s[i]);
304 strbuf_addch(out, '"');
307 enum rfc2047_type {
308 RFC2047_SUBJECT,
309 RFC2047_ADDRESS
312 static int is_rfc2047_special(char ch, enum rfc2047_type type)
315 * rfc2047, section 4.2:
317 * 8-bit values which correspond to printable ASCII characters other
318 * than "=", "?", and "_" (underscore), MAY be represented as those
319 * characters. (But see section 5 for restrictions.) In
320 * particular, SPACE and TAB MUST NOT be represented as themselves
321 * within encoded words.
325 * rule out non-ASCII characters and non-printable characters (the
326 * non-ASCII check should be redundant as isprint() is not localized
327 * and only knows about ASCII, but be defensive about that)
329 if (non_ascii(ch) || !isprint(ch))
330 return 1;
333 * rule out special printable characters (' ' should be the only
334 * whitespace character considered printable, but be defensive and use
335 * isspace())
337 if (isspace(ch) || ch == '=' || ch == '?' || ch == '_')
338 return 1;
341 * rfc2047, section 5.3:
343 * As a replacement for a 'word' entity within a 'phrase', for example,
344 * one that precedes an address in a From, To, or Cc header. The ABNF
345 * definition for 'phrase' from RFC 822 thus becomes:
347 * phrase = 1*( encoded-word / word )
349 * In this case the set of characters that may be used in a "Q"-encoded
350 * 'encoded-word' is restricted to: <upper and lower case ASCII
351 * letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
352 * (underscore, ASCII 95.)>. An 'encoded-word' that appears within a
353 * 'phrase' MUST be separated from any adjacent 'word', 'text' or
354 * 'special' by 'linear-white-space'.
357 if (type != RFC2047_ADDRESS)
358 return 0;
360 /* '=' and '_' are special cases and have been checked above */
361 return !(isalnum(ch) || ch == '!' || ch == '*' || ch == '+' || ch == '-' || ch == '/');
364 static int needs_rfc2047_encoding(const char *line, int len)
366 int i;
368 for (i = 0; i < len; i++) {
369 int ch = line[i];
370 if (non_ascii(ch) || ch == '\n')
371 return 1;
372 if ((i + 1 < len) && (ch == '=' && line[i+1] == '?'))
373 return 1;
376 return 0;
379 static void add_rfc2047(struct strbuf *sb, const char *line, size_t len,
380 const char *encoding, enum rfc2047_type type)
382 static const int max_encoded_length = 76; /* per rfc2047 */
383 int i;
384 int line_len = last_line_length(sb);
386 strbuf_grow(sb, len * 3 + strlen(encoding) + 100);
387 strbuf_addf(sb, "=?%s?q?", encoding);
388 line_len += strlen(encoding) + 5; /* 5 for =??q? */
390 while (len) {
392 * RFC 2047, section 5 (3):
394 * Each 'encoded-word' MUST represent an integral number of
395 * characters. A multi-octet character may not be split across
396 * adjacent 'encoded- word's.
398 const unsigned char *p = (const unsigned char *)line;
399 int chrlen = mbs_chrlen(&line, &len, encoding);
400 int is_special = (chrlen > 1) || is_rfc2047_special(*p, type);
402 /* "=%02X" * chrlen, or the byte itself */
403 const char *encoded_fmt = is_special ? "=%02X" : "%c";
404 int encoded_len = is_special ? 3 * chrlen : 1;
407 * According to RFC 2047, we could encode the special character
408 * ' ' (space) with '_' (underscore) for readability. But many
409 * programs do not understand this and just leave the
410 * underscore in place. Thus, we do nothing special here, which
411 * causes ' ' to be encoded as '=20', avoiding this problem.
414 if (line_len + encoded_len + 2 > max_encoded_length) {
415 /* It won't fit with trailing "?=" --- break the line */
416 strbuf_addf(sb, "?=\n =?%s?q?", encoding);
417 line_len = strlen(encoding) + 5 + 1; /* =??q? plus SP */
420 for (i = 0; i < chrlen; i++)
421 strbuf_addf(sb, encoded_fmt, p[i]);
422 line_len += encoded_len;
424 strbuf_addstr(sb, "?=");
427 const char *show_ident_date(const struct ident_split *ident,
428 const struct date_mode *mode)
430 timestamp_t date = 0;
431 long tz = 0;
433 if (ident->date_begin && ident->date_end)
434 date = parse_timestamp(ident->date_begin, NULL, 10);
435 if (date_overflows(date))
436 date = 0;
437 else {
438 if (ident->tz_begin && ident->tz_end)
439 tz = strtol(ident->tz_begin, NULL, 10);
440 if (tz >= INT_MAX || tz <= INT_MIN)
441 tz = 0;
443 return show_date(date, tz, mode);
446 static inline void strbuf_add_with_color(struct strbuf *sb, const char *color,
447 const char *buf, size_t buflen)
449 strbuf_addstr(sb, color);
450 strbuf_add(sb, buf, buflen);
451 if (*color)
452 strbuf_addstr(sb, GIT_COLOR_RESET);
455 static void append_line_with_color(struct strbuf *sb, struct grep_opt *opt,
456 const char *line, size_t linelen,
457 int color, enum grep_context ctx,
458 enum grep_header_field field)
460 const char *buf, *eol, *line_color, *match_color;
461 regmatch_t match;
462 int eflags = 0;
464 buf = line;
465 eol = buf + linelen;
467 if (!opt || !want_color(color) || opt->invert)
468 goto end;
470 line_color = opt->colors[GREP_COLOR_SELECTED];
471 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
473 while (grep_next_match(opt, buf, eol, ctx, &match, field, eflags)) {
474 if (match.rm_so == match.rm_eo)
475 break;
477 strbuf_add_with_color(sb, line_color, buf, match.rm_so);
478 strbuf_add_with_color(sb, match_color, buf + match.rm_so,
479 match.rm_eo - match.rm_so);
480 buf += match.rm_eo;
481 eflags = REG_NOTBOL;
484 if (eflags)
485 strbuf_add_with_color(sb, line_color, buf, eol - buf);
486 else {
487 end:
488 strbuf_add(sb, buf, eol - buf);
492 static int use_in_body_from(const struct pretty_print_context *pp,
493 const struct ident_split *ident)
495 if (pp->rev && pp->rev->force_in_body_from)
496 return 1;
497 if (ident_cmp(pp->from_ident, ident))
498 return 1;
499 return 0;
502 void pp_user_info(struct pretty_print_context *pp,
503 const char *what, struct strbuf *sb,
504 const char *line, const char *encoding)
506 struct ident_split ident;
507 char *line_end;
508 const char *mailbuf, *namebuf;
509 size_t namelen, maillen;
510 int max_length = 78; /* per rfc2822 */
512 if (pp->fmt == CMIT_FMT_ONELINE)
513 return;
515 line_end = strchrnul(line, '\n');
516 if (split_ident_line(&ident, line, line_end - line))
517 return;
519 mailbuf = ident.mail_begin;
520 maillen = ident.mail_end - ident.mail_begin;
521 namebuf = ident.name_begin;
522 namelen = ident.name_end - ident.name_begin;
524 if (pp->mailmap)
525 map_user(pp->mailmap, &mailbuf, &maillen, &namebuf, &namelen);
527 if (cmit_fmt_is_mail(pp->fmt)) {
528 if (pp->from_ident && use_in_body_from(pp, &ident)) {
529 struct strbuf buf = STRBUF_INIT;
531 strbuf_addstr(&buf, "From: ");
532 strbuf_add(&buf, namebuf, namelen);
533 strbuf_addstr(&buf, " <");
534 strbuf_add(&buf, mailbuf, maillen);
535 strbuf_addstr(&buf, ">\n");
536 string_list_append(&pp->in_body_headers,
537 strbuf_detach(&buf, NULL));
539 mailbuf = pp->from_ident->mail_begin;
540 maillen = pp->from_ident->mail_end - mailbuf;
541 namebuf = pp->from_ident->name_begin;
542 namelen = pp->from_ident->name_end - namebuf;
545 strbuf_addstr(sb, "From: ");
546 if (pp->encode_email_headers &&
547 needs_rfc2047_encoding(namebuf, namelen)) {
548 add_rfc2047(sb, namebuf, namelen,
549 encoding, RFC2047_ADDRESS);
550 max_length = 76; /* per rfc2047 */
551 } else if (needs_rfc822_quoting(namebuf, namelen)) {
552 struct strbuf quoted = STRBUF_INIT;
553 add_rfc822_quoted(&quoted, namebuf, namelen);
554 strbuf_add_wrapped_bytes(sb, quoted.buf, quoted.len,
555 -6, 1, max_length);
556 strbuf_release(&quoted);
557 } else {
558 strbuf_add_wrapped_bytes(sb, namebuf, namelen,
559 -6, 1, max_length);
562 if (max_length <
563 last_line_length(sb) + strlen(" <") + maillen + strlen(">"))
564 strbuf_addch(sb, '\n');
565 strbuf_addf(sb, " <%.*s>\n", (int)maillen, mailbuf);
566 } else {
567 struct strbuf id = STRBUF_INIT;
568 enum grep_header_field field = GREP_HEADER_FIELD_MAX;
569 struct grep_opt *opt = pp->rev ? &pp->rev->grep_filter : NULL;
571 if (!strcmp(what, "Author"))
572 field = GREP_HEADER_AUTHOR;
573 else if (!strcmp(what, "Commit"))
574 field = GREP_HEADER_COMMITTER;
576 strbuf_addf(sb, "%s: ", what);
577 if (pp->fmt == CMIT_FMT_FULLER)
578 strbuf_addchars(sb, ' ', 4);
580 strbuf_addf(&id, "%.*s <%.*s>", (int)namelen, namebuf,
581 (int)maillen, mailbuf);
583 append_line_with_color(sb, opt, id.buf, id.len, pp->color,
584 GREP_CONTEXT_HEAD, field);
585 strbuf_addch(sb, '\n');
586 strbuf_release(&id);
589 switch (pp->fmt) {
590 case CMIT_FMT_MEDIUM:
591 strbuf_addf(sb, "Date: %s\n",
592 show_ident_date(&ident, &pp->date_mode));
593 break;
594 case CMIT_FMT_EMAIL:
595 case CMIT_FMT_MBOXRD:
596 strbuf_addf(sb, "Date: %s\n",
597 show_ident_date(&ident, DATE_MODE(RFC2822)));
598 break;
599 case CMIT_FMT_FULLER:
600 strbuf_addf(sb, "%sDate: %s\n", what,
601 show_ident_date(&ident, &pp->date_mode));
602 break;
603 default:
604 /* notin' */
605 break;
609 static int is_blank_line(const char *line, int *len_p)
611 int len = *len_p;
612 while (len && isspace(line[len - 1]))
613 len--;
614 *len_p = len;
615 return !len;
618 const char *skip_blank_lines(const char *msg)
620 for (;;) {
621 int linelen = get_one_line(msg);
622 int ll = linelen;
623 if (!linelen)
624 break;
625 if (!is_blank_line(msg, &ll))
626 break;
627 msg += linelen;
629 return msg;
632 static void add_merge_info(const struct pretty_print_context *pp,
633 struct strbuf *sb, const struct commit *commit)
635 struct commit_list *parent = commit->parents;
637 if ((pp->fmt == CMIT_FMT_ONELINE) || (cmit_fmt_is_mail(pp->fmt)) ||
638 !parent || !parent->next)
639 return;
641 strbuf_addstr(sb, "Merge:");
643 while (parent) {
644 struct object_id *oidp = &parent->item->object.oid;
645 strbuf_addch(sb, ' ');
646 if (pp->abbrev)
647 strbuf_add_unique_abbrev(sb, oidp, pp->abbrev);
648 else
649 strbuf_addstr(sb, oid_to_hex(oidp));
650 parent = parent->next;
652 strbuf_addch(sb, '\n');
655 static char *get_header(const char *msg, const char *key)
657 size_t len;
658 const char *v = find_commit_header(msg, key, &len);
659 return v ? xmemdupz(v, len) : NULL;
662 static char *replace_encoding_header(char *buf, const char *encoding)
664 struct strbuf tmp = STRBUF_INIT;
665 size_t start, len;
666 char *cp = buf;
668 /* guess if there is an encoding header before a \n\n */
669 while (!starts_with(cp, "encoding ")) {
670 cp = strchr(cp, '\n');
671 if (!cp || *++cp == '\n')
672 return buf;
674 start = cp - buf;
675 cp = strchr(cp, '\n');
676 if (!cp)
677 return buf; /* should not happen but be defensive */
678 len = cp + 1 - (buf + start);
680 strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
681 if (is_encoding_utf8(encoding)) {
682 /* we have re-coded to UTF-8; drop the header */
683 strbuf_remove(&tmp, start, len);
684 } else {
685 /* just replaces XXXX in 'encoding XXXX\n' */
686 strbuf_splice(&tmp, start + strlen("encoding "),
687 len - strlen("encoding \n"),
688 encoding, strlen(encoding));
690 return strbuf_detach(&tmp, NULL);
693 const char *repo_logmsg_reencode(struct repository *r,
694 const struct commit *commit,
695 char **commit_encoding,
696 const char *output_encoding)
698 static const char *utf8 = "UTF-8";
699 const char *use_encoding;
700 char *encoding;
701 const char *msg = repo_get_commit_buffer(r, commit, NULL);
702 char *out;
704 if (!output_encoding || !*output_encoding) {
705 if (commit_encoding)
706 *commit_encoding = get_header(msg, "encoding");
707 return msg;
709 encoding = get_header(msg, "encoding");
710 if (commit_encoding)
711 *commit_encoding = encoding;
712 use_encoding = encoding ? encoding : utf8;
713 if (same_encoding(use_encoding, output_encoding)) {
715 * No encoding work to be done. If we have no encoding header
716 * at all, then there's nothing to do, and we can return the
717 * message verbatim (whether newly allocated or not).
719 if (!encoding)
720 return msg;
723 * Otherwise, we still want to munge the encoding header in the
724 * result, which will be done by modifying the buffer. If we
725 * are using a fresh copy, we can reuse it. But if we are using
726 * the cached copy from repo_get_commit_buffer, we need to duplicate it
727 * to avoid munging the cached copy.
729 if (msg == get_cached_commit_buffer(r, commit, NULL))
730 out = xstrdup(msg);
731 else
732 out = (char *)msg;
734 else {
736 * There's actual encoding work to do. Do the reencoding, which
737 * still leaves the header to be replaced in the next step. At
738 * this point, we are done with msg. If we allocated a fresh
739 * copy, we can free it.
741 out = reencode_string(msg, output_encoding, use_encoding);
742 if (out)
743 repo_unuse_commit_buffer(r, commit, msg);
747 * This replacement actually consumes the buffer we hand it, so we do
748 * not have to worry about freeing the old "out" here.
750 if (out)
751 out = replace_encoding_header(out, output_encoding);
753 if (!commit_encoding)
754 free(encoding);
756 * If the re-encoding failed, out might be NULL here; in that
757 * case we just return the commit message verbatim.
759 return out ? out : msg;
762 static int mailmap_name(const char **email, size_t *email_len,
763 const char **name, size_t *name_len)
765 static struct string_list *mail_map;
766 if (!mail_map) {
767 CALLOC_ARRAY(mail_map, 1);
768 read_mailmap(mail_map);
770 return mail_map->nr && map_user(mail_map, email, email_len, name, name_len);
773 static size_t format_person_part(struct strbuf *sb, char part,
774 const char *msg, int len,
775 const struct date_mode *dmode)
777 /* currently all placeholders have same length */
778 const int placeholder_len = 2;
779 struct ident_split s;
780 const char *name, *mail;
781 size_t maillen, namelen;
783 if (split_ident_line(&s, msg, len) < 0)
784 goto skip;
786 name = s.name_begin;
787 namelen = s.name_end - s.name_begin;
788 mail = s.mail_begin;
789 maillen = s.mail_end - s.mail_begin;
791 if (part == 'N' || part == 'E' || part == 'L') /* mailmap lookup */
792 mailmap_name(&mail, &maillen, &name, &namelen);
793 if (part == 'n' || part == 'N') { /* name */
794 strbuf_add(sb, name, namelen);
795 return placeholder_len;
797 if (part == 'e' || part == 'E') { /* email */
798 strbuf_add(sb, mail, maillen);
799 return placeholder_len;
801 if (part == 'l' || part == 'L') { /* local-part */
802 const char *at = memchr(mail, '@', maillen);
803 if (at)
804 maillen = at - mail;
805 strbuf_add(sb, mail, maillen);
806 return placeholder_len;
809 if (!s.date_begin)
810 goto skip;
812 if (part == 't') { /* date, UNIX timestamp */
813 strbuf_add(sb, s.date_begin, s.date_end - s.date_begin);
814 return placeholder_len;
817 switch (part) {
818 case 'd': /* date */
819 strbuf_addstr(sb, show_ident_date(&s, dmode));
820 return placeholder_len;
821 case 'D': /* date, RFC2822 style */
822 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RFC2822)));
823 return placeholder_len;
824 case 'r': /* date, relative */
825 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RELATIVE)));
826 return placeholder_len;
827 case 'i': /* date, ISO 8601-like */
828 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601)));
829 return placeholder_len;
830 case 'I': /* date, ISO 8601 strict */
831 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601_STRICT)));
832 return placeholder_len;
833 case 'h': /* date, human */
834 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(HUMAN)));
835 return placeholder_len;
836 case 's':
837 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(SHORT)));
838 return placeholder_len;
841 skip:
843 * reading from either a bogus commit, or a reflog entry with
844 * %gn, %ge, etc.; 'sb' cannot be updated, but we still need
845 * to compute a valid return value.
847 if (part == 'n' || part == 'e' || part == 't' || part == 'd'
848 || part == 'D' || part == 'r' || part == 'i')
849 return placeholder_len;
851 return 0; /* unknown placeholder */
854 struct chunk {
855 size_t off;
856 size_t len;
859 enum flush_type {
860 no_flush,
861 flush_right,
862 flush_left,
863 flush_left_and_steal,
864 flush_both
867 enum trunc_type {
868 trunc_none,
869 trunc_left,
870 trunc_middle,
871 trunc_right
874 struct format_commit_context {
875 struct repository *repository;
876 const struct commit *commit;
877 const struct pretty_print_context *pretty_ctx;
878 unsigned commit_header_parsed:1;
879 unsigned commit_message_parsed:1;
880 struct signature_check signature_check;
881 enum flush_type flush_type;
882 enum trunc_type truncate;
883 const char *message;
884 char *commit_encoding;
885 size_t width, indent1, indent2;
886 int auto_color;
887 int padding;
889 /* These offsets are relative to the start of the commit message. */
890 struct chunk author;
891 struct chunk committer;
892 size_t message_off;
893 size_t subject_off;
894 size_t body_off;
896 /* The following ones are relative to the result struct strbuf. */
897 size_t wrap_start;
900 static void parse_commit_header(struct format_commit_context *context)
902 const char *msg = context->message;
903 int i;
905 for (i = 0; msg[i]; i++) {
906 const char *name;
907 int eol;
908 for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
909 ; /* do nothing */
911 if (i == eol) {
912 break;
913 } else if (skip_prefix(msg + i, "author ", &name)) {
914 context->author.off = name - msg;
915 context->author.len = msg + eol - name;
916 } else if (skip_prefix(msg + i, "committer ", &name)) {
917 context->committer.off = name - msg;
918 context->committer.len = msg + eol - name;
920 i = eol;
922 context->message_off = i;
923 context->commit_header_parsed = 1;
926 static int istitlechar(char c)
928 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
929 (c >= '0' && c <= '9') || c == '.' || c == '_';
932 void format_sanitized_subject(struct strbuf *sb, const char *msg, size_t len)
934 size_t trimlen;
935 size_t start_len = sb->len;
936 int space = 2;
937 int i;
939 for (i = 0; i < len; i++) {
940 if (istitlechar(msg[i])) {
941 if (space == 1)
942 strbuf_addch(sb, '-');
943 space = 0;
944 strbuf_addch(sb, msg[i]);
945 if (msg[i] == '.')
946 while (msg[i+1] == '.')
947 i++;
948 } else
949 space |= 1;
952 /* trim any trailing '.' or '-' characters */
953 trimlen = 0;
954 while (sb->len - trimlen > start_len &&
955 (sb->buf[sb->len - 1 - trimlen] == '.'
956 || sb->buf[sb->len - 1 - trimlen] == '-'))
957 trimlen++;
958 strbuf_remove(sb, sb->len - trimlen, trimlen);
961 const char *format_subject(struct strbuf *sb, const char *msg,
962 const char *line_separator)
964 int first = 1;
966 for (;;) {
967 const char *line = msg;
968 int linelen = get_one_line(line);
970 msg += linelen;
971 if (!linelen || is_blank_line(line, &linelen))
972 break;
974 if (!sb)
975 continue;
976 strbuf_grow(sb, linelen + 2);
977 if (!first)
978 strbuf_addstr(sb, line_separator);
979 strbuf_add(sb, line, linelen);
980 first = 0;
982 return msg;
985 static void parse_commit_message(struct format_commit_context *c)
987 const char *msg = c->message + c->message_off;
988 const char *start = c->message;
990 msg = skip_blank_lines(msg);
991 c->subject_off = msg - start;
993 msg = format_subject(NULL, msg, NULL);
994 msg = skip_blank_lines(msg);
995 c->body_off = msg - start;
997 c->commit_message_parsed = 1;
1000 static void strbuf_wrap(struct strbuf *sb, size_t pos,
1001 size_t width, size_t indent1, size_t indent2)
1003 struct strbuf tmp = STRBUF_INIT;
1005 if (pos)
1006 strbuf_add(&tmp, sb->buf, pos);
1007 strbuf_add_wrapped_text(&tmp, sb->buf + pos,
1008 cast_size_t_to_int(indent1),
1009 cast_size_t_to_int(indent2),
1010 cast_size_t_to_int(width));
1011 strbuf_swap(&tmp, sb);
1012 strbuf_release(&tmp);
1015 static void rewrap_message_tail(struct strbuf *sb,
1016 struct format_commit_context *c,
1017 size_t new_width, size_t new_indent1,
1018 size_t new_indent2)
1020 if (c->width == new_width && c->indent1 == new_indent1 &&
1021 c->indent2 == new_indent2)
1022 return;
1023 if (c->wrap_start < sb->len)
1024 strbuf_wrap(sb, c->wrap_start, c->width, c->indent1, c->indent2);
1025 c->wrap_start = sb->len;
1026 c->width = new_width;
1027 c->indent1 = new_indent1;
1028 c->indent2 = new_indent2;
1031 static int format_reflog_person(struct strbuf *sb,
1032 char part,
1033 struct reflog_walk_info *log,
1034 const struct date_mode *dmode)
1036 const char *ident;
1038 if (!log)
1039 return 2;
1041 ident = get_reflog_ident(log);
1042 if (!ident)
1043 return 2;
1045 return format_person_part(sb, part, ident, strlen(ident), dmode);
1048 static size_t parse_color(struct strbuf *sb, /* in UTF-8 */
1049 const char *placeholder,
1050 struct format_commit_context *c)
1052 const char *rest = placeholder;
1053 const char *basic_color = NULL;
1055 if (placeholder[1] == '(') {
1056 const char *begin = placeholder + 2;
1057 const char *end = strchr(begin, ')');
1058 char color[COLOR_MAXLEN];
1060 if (!end)
1061 return 0;
1063 if (skip_prefix(begin, "auto,", &begin)) {
1064 if (!want_color(c->pretty_ctx->color))
1065 return end - placeholder + 1;
1066 } else if (skip_prefix(begin, "always,", &begin)) {
1067 /* nothing to do; we do not respect want_color at all */
1068 } else {
1069 /* the default is the same as "auto" */
1070 if (!want_color(c->pretty_ctx->color))
1071 return end - placeholder + 1;
1074 if (color_parse_mem(begin, end - begin, color) < 0)
1075 die(_("unable to parse --pretty format"));
1076 strbuf_addstr(sb, color);
1077 return end - placeholder + 1;
1081 * We handle things like "%C(red)" above; for historical reasons, there
1082 * are a few colors that can be specified without parentheses (and
1083 * they cannot support things like "auto" or "always" at all).
1085 if (skip_prefix(placeholder + 1, "red", &rest))
1086 basic_color = GIT_COLOR_RED;
1087 else if (skip_prefix(placeholder + 1, "green", &rest))
1088 basic_color = GIT_COLOR_GREEN;
1089 else if (skip_prefix(placeholder + 1, "blue", &rest))
1090 basic_color = GIT_COLOR_BLUE;
1091 else if (skip_prefix(placeholder + 1, "reset", &rest))
1092 basic_color = GIT_COLOR_RESET;
1094 if (basic_color && want_color(c->pretty_ctx->color))
1095 strbuf_addstr(sb, basic_color);
1097 return rest - placeholder;
1100 static size_t parse_padding_placeholder(const char *placeholder,
1101 struct format_commit_context *c)
1103 const char *ch = placeholder;
1104 enum flush_type flush_type;
1105 int to_column = 0;
1107 switch (*ch++) {
1108 case '<':
1109 flush_type = flush_right;
1110 break;
1111 case '>':
1112 if (*ch == '<') {
1113 flush_type = flush_both;
1114 ch++;
1115 } else if (*ch == '>') {
1116 flush_type = flush_left_and_steal;
1117 ch++;
1118 } else
1119 flush_type = flush_left;
1120 break;
1121 default:
1122 return 0;
1125 /* the next value means "wide enough to that column" */
1126 if (*ch == '|') {
1127 to_column = 1;
1128 ch++;
1131 if (*ch == '(') {
1132 const char *start = ch + 1;
1133 const char *end = start + strcspn(start, ",)");
1134 char *next;
1135 int width;
1136 if (!*end || end == start)
1137 return 0;
1138 width = strtol(start, &next, 10);
1141 * We need to limit the amount of padding, or otherwise this
1142 * would allow the user to pad the buffer by arbitrarily many
1143 * bytes and thus cause resource exhaustion.
1145 if (width < -FORMATTING_LIMIT || width > FORMATTING_LIMIT)
1146 return 0;
1148 if (next == start || width == 0)
1149 return 0;
1150 if (width < 0) {
1151 if (to_column)
1152 width += term_columns();
1153 if (width < 0)
1154 return 0;
1156 c->padding = to_column ? -width : width;
1157 c->flush_type = flush_type;
1159 if (*end == ',') {
1160 start = end + 1;
1161 end = strchr(start, ')');
1162 if (!end || end == start)
1163 return 0;
1164 if (starts_with(start, "trunc)"))
1165 c->truncate = trunc_right;
1166 else if (starts_with(start, "ltrunc)"))
1167 c->truncate = trunc_left;
1168 else if (starts_with(start, "mtrunc)"))
1169 c->truncate = trunc_middle;
1170 else
1171 return 0;
1172 } else
1173 c->truncate = trunc_none;
1175 return end - placeholder + 1;
1177 return 0;
1180 static int match_placeholder_arg_value(const char *to_parse, const char *candidate,
1181 const char **end, const char **valuestart,
1182 size_t *valuelen)
1184 const char *p;
1186 if (!(skip_prefix(to_parse, candidate, &p)))
1187 return 0;
1188 if (valuestart) {
1189 if (*p == '=') {
1190 *valuestart = p + 1;
1191 *valuelen = strcspn(*valuestart, ",)");
1192 p = *valuestart + *valuelen;
1193 } else {
1194 if (*p != ',' && *p != ')')
1195 return 0;
1196 *valuestart = NULL;
1197 *valuelen = 0;
1200 if (*p == ',') {
1201 *end = p + 1;
1202 return 1;
1204 if (*p == ')') {
1205 *end = p;
1206 return 1;
1208 return 0;
1211 static int match_placeholder_bool_arg(const char *to_parse, const char *candidate,
1212 const char **end, int *val)
1214 const char *argval;
1215 char *strval;
1216 size_t arglen;
1217 int v;
1219 if (!match_placeholder_arg_value(to_parse, candidate, end, &argval, &arglen))
1220 return 0;
1222 if (!argval) {
1223 *val = 1;
1224 return 1;
1227 strval = xstrndup(argval, arglen);
1228 v = git_parse_maybe_bool(strval);
1229 free(strval);
1231 if (v == -1)
1232 return 0;
1234 *val = v;
1236 return 1;
1239 static int format_trailer_match_cb(const struct strbuf *key, void *ud)
1241 const struct string_list *list = ud;
1242 const struct string_list_item *item;
1244 for_each_string_list_item (item, list) {
1245 if (key->len == (uintptr_t)item->util &&
1246 !strncasecmp(item->string, key->buf, key->len))
1247 return 1;
1249 return 0;
1252 int format_set_trailers_options(struct process_trailer_options *opts,
1253 struct string_list *filter_list,
1254 struct strbuf *sepbuf,
1255 struct strbuf *kvsepbuf,
1256 const char **arg,
1257 char **invalid_arg)
1259 for (;;) {
1260 const char *argval;
1261 size_t arglen;
1263 if (**arg == ')')
1264 break;
1266 if (match_placeholder_arg_value(*arg, "key", arg, &argval, &arglen)) {
1267 uintptr_t len = arglen;
1269 if (!argval)
1270 return -1;
1272 if (len && argval[len - 1] == ':')
1273 len--;
1274 string_list_append(filter_list, argval)->util = (char *)len;
1276 opts->filter = format_trailer_match_cb;
1277 opts->filter_data = filter_list;
1278 opts->only_trailers = 1;
1279 } else if (match_placeholder_arg_value(*arg, "separator", arg, &argval, &arglen)) {
1280 char *fmt;
1282 strbuf_reset(sepbuf);
1283 fmt = xstrndup(argval, arglen);
1284 strbuf_expand(sepbuf, fmt, strbuf_expand_literal_cb, NULL);
1285 free(fmt);
1286 opts->separator = sepbuf;
1287 } else if (match_placeholder_arg_value(*arg, "key_value_separator", arg, &argval, &arglen)) {
1288 char *fmt;
1290 strbuf_reset(kvsepbuf);
1291 fmt = xstrndup(argval, arglen);
1292 strbuf_expand(kvsepbuf, fmt, strbuf_expand_literal_cb, NULL);
1293 free(fmt);
1294 opts->key_value_separator = kvsepbuf;
1295 } else if (!match_placeholder_bool_arg(*arg, "only", arg, &opts->only_trailers) &&
1296 !match_placeholder_bool_arg(*arg, "unfold", arg, &opts->unfold) &&
1297 !match_placeholder_bool_arg(*arg, "keyonly", arg, &opts->key_only) &&
1298 !match_placeholder_bool_arg(*arg, "valueonly", arg, &opts->value_only)) {
1299 if (invalid_arg) {
1300 size_t len = strcspn(*arg, ",)");
1301 *invalid_arg = xstrndup(*arg, len);
1303 return -1;
1306 return 0;
1309 static size_t parse_describe_args(const char *start, struct strvec *args)
1311 struct {
1312 char *name;
1313 enum {
1314 DESCRIBE_ARG_BOOL,
1315 DESCRIBE_ARG_INTEGER,
1316 DESCRIBE_ARG_STRING,
1317 } type;
1318 } option[] = {
1319 { "tags", DESCRIBE_ARG_BOOL},
1320 { "abbrev", DESCRIBE_ARG_INTEGER },
1321 { "exclude", DESCRIBE_ARG_STRING },
1322 { "match", DESCRIBE_ARG_STRING },
1324 const char *arg = start;
1326 for (;;) {
1327 int found = 0;
1328 const char *argval;
1329 size_t arglen = 0;
1330 int optval = 0;
1331 int i;
1333 for (i = 0; !found && i < ARRAY_SIZE(option); i++) {
1334 switch (option[i].type) {
1335 case DESCRIBE_ARG_BOOL:
1336 if (match_placeholder_bool_arg(arg, option[i].name, &arg, &optval)) {
1337 if (optval)
1338 strvec_pushf(args, "--%s", option[i].name);
1339 else
1340 strvec_pushf(args, "--no-%s", option[i].name);
1341 found = 1;
1343 break;
1344 case DESCRIBE_ARG_INTEGER:
1345 if (match_placeholder_arg_value(arg, option[i].name, &arg,
1346 &argval, &arglen)) {
1347 char *endptr;
1348 if (!arglen)
1349 return 0;
1350 strtol(argval, &endptr, 10);
1351 if (endptr - argval != arglen)
1352 return 0;
1353 strvec_pushf(args, "--%s=%.*s", option[i].name, (int)arglen, argval);
1354 found = 1;
1356 break;
1357 case DESCRIBE_ARG_STRING:
1358 if (match_placeholder_arg_value(arg, option[i].name, &arg,
1359 &argval, &arglen)) {
1360 if (!arglen)
1361 return 0;
1362 strvec_pushf(args, "--%s=%.*s", option[i].name, (int)arglen, argval);
1363 found = 1;
1365 break;
1368 if (!found)
1369 break;
1372 return arg - start;
1375 static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
1376 const char *placeholder,
1377 void *context)
1379 struct format_commit_context *c = context;
1380 const struct commit *commit = c->commit;
1381 const char *msg = c->message;
1382 struct commit_list *p;
1383 const char *arg, *eol;
1384 size_t res;
1385 char **slot;
1387 /* these are independent of the commit */
1388 res = strbuf_expand_literal_cb(sb, placeholder, NULL);
1389 if (res)
1390 return res;
1392 switch (placeholder[0]) {
1393 case 'C':
1394 if (starts_with(placeholder + 1, "(auto)")) {
1395 c->auto_color = want_color(c->pretty_ctx->color);
1396 if (c->auto_color && sb->len)
1397 strbuf_addstr(sb, GIT_COLOR_RESET);
1398 return 7; /* consumed 7 bytes, "C(auto)" */
1399 } else {
1400 int ret = parse_color(sb, placeholder, c);
1401 if (ret)
1402 c->auto_color = 0;
1404 * Otherwise, we decided to treat %C<unknown>
1405 * as a literal string, and the previous
1406 * %C(auto) is still valid.
1408 return ret;
1410 case 'w':
1411 if (placeholder[1] == '(') {
1412 unsigned long width = 0, indent1 = 0, indent2 = 0;
1413 char *next;
1414 const char *start = placeholder + 2;
1415 const char *end = strchr(start, ')');
1416 if (!end)
1417 return 0;
1418 if (end > start) {
1419 width = strtoul(start, &next, 10);
1420 if (*next == ',') {
1421 indent1 = strtoul(next + 1, &next, 10);
1422 if (*next == ',') {
1423 indent2 = strtoul(next + 1,
1424 &next, 10);
1427 if (*next != ')')
1428 return 0;
1432 * We need to limit the format here as it allows the
1433 * user to prepend arbitrarily many bytes to the buffer
1434 * when rewrapping.
1436 if (width > FORMATTING_LIMIT ||
1437 indent1 > FORMATTING_LIMIT ||
1438 indent2 > FORMATTING_LIMIT)
1439 return 0;
1440 rewrap_message_tail(sb, c, width, indent1, indent2);
1441 return end - placeholder + 1;
1442 } else
1443 return 0;
1445 case '<':
1446 case '>':
1447 return parse_padding_placeholder(placeholder, c);
1450 if (skip_prefix(placeholder, "(describe", &arg)) {
1451 struct child_process cmd = CHILD_PROCESS_INIT;
1452 struct strbuf out = STRBUF_INIT;
1453 struct strbuf err = STRBUF_INIT;
1454 struct pretty_print_describe_status *describe_status;
1456 describe_status = c->pretty_ctx->describe_status;
1457 if (describe_status) {
1458 if (!describe_status->max_invocations)
1459 return 0;
1460 describe_status->max_invocations--;
1463 cmd.git_cmd = 1;
1464 strvec_push(&cmd.args, "describe");
1466 if (*arg == ':') {
1467 arg++;
1468 arg += parse_describe_args(arg, &cmd.args);
1471 if (*arg != ')') {
1472 child_process_clear(&cmd);
1473 return 0;
1476 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1477 pipe_command(&cmd, NULL, 0, &out, 0, &err, 0);
1478 strbuf_rtrim(&out);
1479 strbuf_addbuf(sb, &out);
1480 strbuf_release(&out);
1481 strbuf_release(&err);
1482 return arg - placeholder + 1;
1485 /* these depend on the commit */
1486 if (!commit->object.parsed)
1487 parse_object(the_repository, &commit->object.oid);
1489 switch (placeholder[0]) {
1490 case 'H': /* commit hash */
1491 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1492 strbuf_addstr(sb, oid_to_hex(&commit->object.oid));
1493 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1494 return 1;
1495 case 'h': /* abbreviated commit hash */
1496 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1497 strbuf_add_unique_abbrev(sb, &commit->object.oid,
1498 c->pretty_ctx->abbrev);
1499 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1500 return 1;
1501 case 'T': /* tree hash */
1502 strbuf_addstr(sb, oid_to_hex(get_commit_tree_oid(commit)));
1503 return 1;
1504 case 't': /* abbreviated tree hash */
1505 strbuf_add_unique_abbrev(sb,
1506 get_commit_tree_oid(commit),
1507 c->pretty_ctx->abbrev);
1508 return 1;
1509 case 'P': /* parent hashes */
1510 for (p = commit->parents; p; p = p->next) {
1511 if (p != commit->parents)
1512 strbuf_addch(sb, ' ');
1513 strbuf_addstr(sb, oid_to_hex(&p->item->object.oid));
1515 return 1;
1516 case 'p': /* abbreviated parent hashes */
1517 for (p = commit->parents; p; p = p->next) {
1518 if (p != commit->parents)
1519 strbuf_addch(sb, ' ');
1520 strbuf_add_unique_abbrev(sb, &p->item->object.oid,
1521 c->pretty_ctx->abbrev);
1523 return 1;
1524 case 'm': /* left/right/bottom */
1525 strbuf_addstr(sb, get_revision_mark(NULL, commit));
1526 return 1;
1527 case 'd':
1528 format_decorations(sb, commit, c->auto_color);
1529 return 1;
1530 case 'D':
1531 format_decorations_extended(sb, commit, c->auto_color, "", ", ", "");
1532 return 1;
1533 case 'S': /* tag/branch like --source */
1534 if (!(c->pretty_ctx->rev && c->pretty_ctx->rev->sources))
1535 return 0;
1536 slot = revision_sources_at(c->pretty_ctx->rev->sources, commit);
1537 if (!(slot && *slot))
1538 return 0;
1539 strbuf_addstr(sb, *slot);
1540 return 1;
1541 case 'g': /* reflog info */
1542 switch(placeholder[1]) {
1543 case 'd': /* reflog selector */
1544 case 'D':
1545 if (c->pretty_ctx->reflog_info)
1546 get_reflog_selector(sb,
1547 c->pretty_ctx->reflog_info,
1548 &c->pretty_ctx->date_mode,
1549 c->pretty_ctx->date_mode_explicit,
1550 (placeholder[1] == 'd'));
1551 return 2;
1552 case 's': /* reflog message */
1553 if (c->pretty_ctx->reflog_info)
1554 get_reflog_message(sb, c->pretty_ctx->reflog_info);
1555 return 2;
1556 case 'n':
1557 case 'N':
1558 case 'e':
1559 case 'E':
1560 return format_reflog_person(sb,
1561 placeholder[1],
1562 c->pretty_ctx->reflog_info,
1563 &c->pretty_ctx->date_mode);
1565 return 0; /* unknown %g placeholder */
1566 case 'N':
1567 if (c->pretty_ctx->notes_message) {
1568 strbuf_addstr(sb, c->pretty_ctx->notes_message);
1569 return 1;
1571 return 0;
1574 if (placeholder[0] == 'G') {
1575 if (!c->signature_check.result)
1576 check_commit_signature(c->commit, &(c->signature_check));
1577 switch (placeholder[1]) {
1578 case 'G':
1579 if (c->signature_check.output)
1580 strbuf_addstr(sb, c->signature_check.output);
1581 break;
1582 case '?':
1583 switch (c->signature_check.result) {
1584 case 'G':
1585 switch (c->signature_check.trust_level) {
1586 case TRUST_UNDEFINED:
1587 case TRUST_NEVER:
1588 strbuf_addch(sb, 'U');
1589 break;
1590 default:
1591 strbuf_addch(sb, 'G');
1592 break;
1594 break;
1595 case 'B':
1596 case 'E':
1597 case 'N':
1598 case 'X':
1599 case 'Y':
1600 case 'R':
1601 strbuf_addch(sb, c->signature_check.result);
1603 break;
1604 case 'S':
1605 if (c->signature_check.signer)
1606 strbuf_addstr(sb, c->signature_check.signer);
1607 break;
1608 case 'K':
1609 if (c->signature_check.key)
1610 strbuf_addstr(sb, c->signature_check.key);
1611 break;
1612 case 'F':
1613 if (c->signature_check.fingerprint)
1614 strbuf_addstr(sb, c->signature_check.fingerprint);
1615 break;
1616 case 'P':
1617 if (c->signature_check.primary_key_fingerprint)
1618 strbuf_addstr(sb, c->signature_check.primary_key_fingerprint);
1619 break;
1620 case 'T':
1621 strbuf_addstr(sb, gpg_trust_level_to_str(c->signature_check.trust_level));
1622 break;
1623 default:
1624 return 0;
1626 return 2;
1629 /* For the rest we have to parse the commit header. */
1630 if (!c->commit_header_parsed) {
1631 msg = c->message =
1632 repo_logmsg_reencode(c->repository, commit,
1633 &c->commit_encoding, "UTF-8");
1634 parse_commit_header(c);
1637 switch (placeholder[0]) {
1638 case 'a': /* author ... */
1639 return format_person_part(sb, placeholder[1],
1640 msg + c->author.off, c->author.len,
1641 &c->pretty_ctx->date_mode);
1642 case 'c': /* committer ... */
1643 return format_person_part(sb, placeholder[1],
1644 msg + c->committer.off, c->committer.len,
1645 &c->pretty_ctx->date_mode);
1646 case 'e': /* encoding */
1647 if (c->commit_encoding)
1648 strbuf_addstr(sb, c->commit_encoding);
1649 return 1;
1650 case 'B': /* raw body */
1651 /* message_off is always left at the initial newline */
1652 strbuf_addstr(sb, msg + c->message_off + 1);
1653 return 1;
1656 /* Now we need to parse the commit message. */
1657 if (!c->commit_message_parsed)
1658 parse_commit_message(c);
1660 switch (placeholder[0]) {
1661 case 's': /* subject */
1662 format_subject(sb, msg + c->subject_off, " ");
1663 return 1;
1664 case 'f': /* sanitized subject */
1665 eol = strchrnul(msg + c->subject_off, '\n');
1666 format_sanitized_subject(sb, msg + c->subject_off, eol - (msg + c->subject_off));
1667 return 1;
1668 case 'b': /* body */
1669 strbuf_addstr(sb, msg + c->body_off);
1670 return 1;
1673 if (skip_prefix(placeholder, "(trailers", &arg)) {
1674 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1675 struct string_list filter_list = STRING_LIST_INIT_NODUP;
1676 struct strbuf sepbuf = STRBUF_INIT;
1677 struct strbuf kvsepbuf = STRBUF_INIT;
1678 size_t ret = 0;
1680 opts.no_divider = 1;
1682 if (*arg == ':') {
1683 arg++;
1684 if (format_set_trailers_options(&opts, &filter_list, &sepbuf, &kvsepbuf, &arg, NULL))
1685 goto trailer_out;
1687 if (*arg == ')') {
1688 format_trailers_from_commit(sb, msg + c->subject_off, &opts);
1689 ret = arg - placeholder + 1;
1691 trailer_out:
1692 string_list_clear(&filter_list, 0);
1693 strbuf_release(&sepbuf);
1694 return ret;
1697 return 0; /* unknown placeholder */
1700 static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */
1701 const char *placeholder,
1702 struct format_commit_context *c)
1704 struct strbuf local_sb = STRBUF_INIT;
1705 size_t total_consumed = 0;
1706 int len, padding = c->padding;
1708 if (padding < 0) {
1709 const char *start = strrchr(sb->buf, '\n');
1710 int occupied;
1711 if (!start)
1712 start = sb->buf;
1713 occupied = utf8_strnwidth(start, strlen(start), 1);
1714 occupied += c->pretty_ctx->graph_width;
1715 padding = (-padding) - occupied;
1717 while (1) {
1718 int modifier = *placeholder == 'C';
1719 size_t consumed = format_commit_one(&local_sb, placeholder, c);
1720 total_consumed += consumed;
1722 if (!modifier)
1723 break;
1725 placeholder += consumed;
1726 if (*placeholder != '%')
1727 break;
1728 placeholder++;
1729 total_consumed++;
1731 len = utf8_strnwidth(local_sb.buf, local_sb.len, 1);
1733 if (c->flush_type == flush_left_and_steal) {
1734 const char *ch = sb->buf + sb->len - 1;
1735 while (len > padding && ch > sb->buf) {
1736 const char *p;
1737 if (*ch == ' ') {
1738 ch--;
1739 padding++;
1740 continue;
1742 /* check for trailing ansi sequences */
1743 if (*ch != 'm')
1744 break;
1745 p = ch - 1;
1746 while (p > sb->buf && ch - p < 10 && *p != '\033')
1747 p--;
1748 if (*p != '\033' ||
1749 ch + 1 - p != display_mode_esc_sequence_len(p))
1750 break;
1752 * got a good ansi sequence, put it back to
1753 * local_sb as we're cutting sb
1755 strbuf_insert(&local_sb, 0, p, ch + 1 - p);
1756 ch = p - 1;
1758 strbuf_setlen(sb, ch + 1 - sb->buf);
1759 c->flush_type = flush_left;
1762 if (len > padding) {
1763 switch (c->truncate) {
1764 case trunc_left:
1765 strbuf_utf8_replace(&local_sb,
1766 0, len - (padding - 2),
1767 "..");
1768 break;
1769 case trunc_middle:
1770 strbuf_utf8_replace(&local_sb,
1771 padding / 2 - 1,
1772 len - (padding - 2),
1773 "..");
1774 break;
1775 case trunc_right:
1776 strbuf_utf8_replace(&local_sb,
1777 padding - 2, len - (padding - 2),
1778 "..");
1779 break;
1780 case trunc_none:
1781 break;
1783 strbuf_addbuf(sb, &local_sb);
1784 } else {
1785 size_t sb_len = sb->len, offset = 0;
1786 if (c->flush_type == flush_left)
1787 offset = padding - len;
1788 else if (c->flush_type == flush_both)
1789 offset = (padding - len) / 2;
1791 * we calculate padding in columns, now
1792 * convert it back to chars
1794 padding = padding - len + local_sb.len;
1795 strbuf_addchars(sb, ' ', padding);
1796 memcpy(sb->buf + sb_len + offset, local_sb.buf,
1797 local_sb.len);
1799 strbuf_release(&local_sb);
1800 c->flush_type = no_flush;
1801 return total_consumed;
1804 static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */
1805 const char *placeholder,
1806 void *context)
1808 size_t consumed, orig_len;
1809 enum {
1810 NO_MAGIC,
1811 ADD_LF_BEFORE_NON_EMPTY,
1812 DEL_LF_BEFORE_EMPTY,
1813 ADD_SP_BEFORE_NON_EMPTY
1814 } magic = NO_MAGIC;
1816 switch (placeholder[0]) {
1817 case '-':
1818 magic = DEL_LF_BEFORE_EMPTY;
1819 break;
1820 case '+':
1821 magic = ADD_LF_BEFORE_NON_EMPTY;
1822 break;
1823 case ' ':
1824 magic = ADD_SP_BEFORE_NON_EMPTY;
1825 break;
1826 default:
1827 break;
1829 if (magic != NO_MAGIC) {
1830 placeholder++;
1832 switch (placeholder[0]) {
1833 case 'w':
1835 * `%+w()` cannot ever expand to a non-empty string,
1836 * and it potentially changes the layout of preceding
1837 * contents. We're thus not able to handle the magic in
1838 * this combination and refuse the pattern.
1840 return 0;
1844 orig_len = sb->len;
1845 if (((struct format_commit_context *)context)->flush_type != no_flush)
1846 consumed = format_and_pad_commit(sb, placeholder, context);
1847 else
1848 consumed = format_commit_one(sb, placeholder, context);
1849 if (magic == NO_MAGIC)
1850 return consumed;
1852 if ((orig_len == sb->len) && magic == DEL_LF_BEFORE_EMPTY) {
1853 while (sb->len && sb->buf[sb->len - 1] == '\n')
1854 strbuf_setlen(sb, sb->len - 1);
1855 } else if (orig_len != sb->len) {
1856 if (magic == ADD_LF_BEFORE_NON_EMPTY)
1857 strbuf_insertstr(sb, orig_len, "\n");
1858 else if (magic == ADD_SP_BEFORE_NON_EMPTY)
1859 strbuf_insertstr(sb, orig_len, " ");
1861 return consumed + 1;
1864 static size_t userformat_want_item(struct strbuf *sb UNUSED,
1865 const char *placeholder,
1866 void *context)
1868 struct userformat_want *w = context;
1870 if (*placeholder == '+' || *placeholder == '-' || *placeholder == ' ')
1871 placeholder++;
1873 switch (*placeholder) {
1874 case 'N':
1875 w->notes = 1;
1876 break;
1877 case 'S':
1878 w->source = 1;
1879 break;
1880 case 'd':
1881 case 'D':
1882 w->decorate = 1;
1883 break;
1885 return 0;
1888 void userformat_find_requirements(const char *fmt, struct userformat_want *w)
1890 struct strbuf dummy = STRBUF_INIT;
1892 if (!fmt) {
1893 if (!user_format)
1894 return;
1895 fmt = user_format;
1897 strbuf_expand(&dummy, fmt, userformat_want_item, w);
1898 strbuf_release(&dummy);
1901 void repo_format_commit_message(struct repository *r,
1902 const struct commit *commit,
1903 const char *format, struct strbuf *sb,
1904 const struct pretty_print_context *pretty_ctx)
1906 struct format_commit_context context = {
1907 .repository = r,
1908 .commit = commit,
1909 .pretty_ctx = pretty_ctx,
1910 .wrap_start = sb->len
1912 const char *output_enc = pretty_ctx->output_encoding;
1913 const char *utf8 = "UTF-8";
1915 strbuf_expand(sb, format, format_commit_item, &context);
1916 rewrap_message_tail(sb, &context, 0, 0, 0);
1919 * Convert output to an actual output encoding; note that
1920 * format_commit_item() will always use UTF-8, so we don't
1921 * have to bother if that's what the output wants.
1923 if (output_enc) {
1924 if (same_encoding(utf8, output_enc))
1925 output_enc = NULL;
1926 } else {
1927 if (context.commit_encoding &&
1928 !same_encoding(context.commit_encoding, utf8))
1929 output_enc = context.commit_encoding;
1932 if (output_enc) {
1933 size_t outsz;
1934 char *out = reencode_string_len(sb->buf, sb->len,
1935 output_enc, utf8, &outsz);
1936 if (out)
1937 strbuf_attach(sb, out, outsz, outsz + 1);
1940 free(context.commit_encoding);
1941 repo_unuse_commit_buffer(r, commit, context.message);
1944 static void pp_header(struct pretty_print_context *pp,
1945 const char *encoding,
1946 const struct commit *commit,
1947 const char **msg_p,
1948 struct strbuf *sb)
1950 int parents_shown = 0;
1952 for (;;) {
1953 const char *name, *line = *msg_p;
1954 int linelen = get_one_line(*msg_p);
1956 if (!linelen)
1957 return;
1958 *msg_p += linelen;
1960 if (linelen == 1)
1961 /* End of header */
1962 return;
1964 if (pp->fmt == CMIT_FMT_RAW) {
1965 strbuf_add(sb, line, linelen);
1966 continue;
1969 if (starts_with(line, "parent ")) {
1970 if (linelen != the_hash_algo->hexsz + 8)
1971 die("bad parent line in commit");
1972 continue;
1975 if (!parents_shown) {
1976 unsigned num = commit_list_count(commit->parents);
1977 /* with enough slop */
1978 strbuf_grow(sb, num * (GIT_MAX_HEXSZ + 10) + 20);
1979 add_merge_info(pp, sb, commit);
1980 parents_shown = 1;
1984 * MEDIUM == DEFAULT shows only author with dates.
1985 * FULL shows both authors but not dates.
1986 * FULLER shows both authors and dates.
1988 if (skip_prefix(line, "author ", &name)) {
1989 strbuf_grow(sb, linelen + 80);
1990 pp_user_info(pp, "Author", sb, name, encoding);
1992 if (skip_prefix(line, "committer ", &name) &&
1993 (pp->fmt == CMIT_FMT_FULL || pp->fmt == CMIT_FMT_FULLER)) {
1994 strbuf_grow(sb, linelen + 80);
1995 pp_user_info(pp, "Commit", sb, name, encoding);
2000 void pp_title_line(struct pretty_print_context *pp,
2001 const char **msg_p,
2002 struct strbuf *sb,
2003 const char *encoding,
2004 int need_8bit_cte)
2006 static const int max_length = 78; /* per rfc2047 */
2007 struct strbuf title;
2009 strbuf_init(&title, 80);
2010 *msg_p = format_subject(&title, *msg_p,
2011 pp->preserve_subject ? "\n" : " ");
2013 strbuf_grow(sb, title.len + 1024);
2014 if (pp->print_email_subject) {
2015 if (pp->rev)
2016 fmt_output_email_subject(sb, pp->rev);
2017 if (pp->encode_email_headers &&
2018 needs_rfc2047_encoding(title.buf, title.len))
2019 add_rfc2047(sb, title.buf, title.len,
2020 encoding, RFC2047_SUBJECT);
2021 else
2022 strbuf_add_wrapped_bytes(sb, title.buf, title.len,
2023 -last_line_length(sb), 1, max_length);
2024 } else {
2025 strbuf_addbuf(sb, &title);
2027 strbuf_addch(sb, '\n');
2029 if (need_8bit_cte == 0) {
2030 int i;
2031 for (i = 0; i < pp->in_body_headers.nr; i++) {
2032 if (has_non_ascii(pp->in_body_headers.items[i].string)) {
2033 need_8bit_cte = 1;
2034 break;
2039 if (need_8bit_cte > 0) {
2040 const char *header_fmt =
2041 "MIME-Version: 1.0\n"
2042 "Content-Type: text/plain; charset=%s\n"
2043 "Content-Transfer-Encoding: 8bit\n";
2044 strbuf_addf(sb, header_fmt, encoding);
2046 if (pp->after_subject) {
2047 strbuf_addstr(sb, pp->after_subject);
2049 if (cmit_fmt_is_mail(pp->fmt)) {
2050 strbuf_addch(sb, '\n');
2053 if (pp->in_body_headers.nr) {
2054 int i;
2055 for (i = 0; i < pp->in_body_headers.nr; i++) {
2056 strbuf_addstr(sb, pp->in_body_headers.items[i].string);
2057 free(pp->in_body_headers.items[i].string);
2059 string_list_clear(&pp->in_body_headers, 0);
2060 strbuf_addch(sb, '\n');
2063 strbuf_release(&title);
2066 static int pp_utf8_width(const char *start, const char *end)
2068 int width = 0;
2069 size_t remain = end - start;
2071 while (remain) {
2072 int n = utf8_width(&start, &remain);
2073 if (n < 0 || !start)
2074 return -1;
2075 width += n;
2077 return width;
2080 static void strbuf_add_tabexpand(struct strbuf *sb, struct grep_opt *opt,
2081 int color, int tabwidth, const char *line,
2082 int linelen)
2084 const char *tab;
2086 while ((tab = memchr(line, '\t', linelen)) != NULL) {
2087 int width = pp_utf8_width(line, tab);
2090 * If it wasn't well-formed utf8, or it
2091 * had characters with badly defined
2092 * width (control characters etc), just
2093 * give up on trying to align things.
2095 if (width < 0)
2096 break;
2098 /* Output the data .. */
2099 append_line_with_color(sb, opt, line, tab - line, color,
2100 GREP_CONTEXT_BODY,
2101 GREP_HEADER_FIELD_MAX);
2103 /* .. and the de-tabified tab */
2104 strbuf_addchars(sb, ' ', tabwidth - (width % tabwidth));
2106 /* Skip over the printed part .. */
2107 linelen -= tab + 1 - line;
2108 line = tab + 1;
2112 * Print out everything after the last tab without
2113 * worrying about width - there's nothing more to
2114 * align.
2116 append_line_with_color(sb, opt, line, linelen, color, GREP_CONTEXT_BODY,
2117 GREP_HEADER_FIELD_MAX);
2121 * pp_handle_indent() prints out the intendation, and
2122 * the whole line (without the final newline), after
2123 * de-tabifying.
2125 static void pp_handle_indent(struct pretty_print_context *pp,
2126 struct strbuf *sb, int indent,
2127 const char *line, int linelen)
2129 struct grep_opt *opt = pp->rev ? &pp->rev->grep_filter : NULL;
2131 strbuf_addchars(sb, ' ', indent);
2132 if (pp->expand_tabs_in_log)
2133 strbuf_add_tabexpand(sb, opt, pp->color, pp->expand_tabs_in_log,
2134 line, linelen);
2135 else
2136 append_line_with_color(sb, opt, line, linelen, pp->color,
2137 GREP_CONTEXT_BODY,
2138 GREP_HEADER_FIELD_MAX);
2141 static int is_mboxrd_from(const char *line, int len)
2144 * a line matching /^From $/ here would only have len == 4
2145 * at this point because is_empty_line would've trimmed all
2146 * trailing space
2148 return len > 4 && starts_with(line + strspn(line, ">"), "From ");
2151 void pp_remainder(struct pretty_print_context *pp,
2152 const char **msg_p,
2153 struct strbuf *sb,
2154 int indent)
2156 struct grep_opt *opt = pp->rev ? &pp->rev->grep_filter : NULL;
2157 int first = 1;
2159 for (;;) {
2160 const char *line = *msg_p;
2161 int linelen = get_one_line(line);
2162 *msg_p += linelen;
2164 if (!linelen)
2165 break;
2167 if (is_blank_line(line, &linelen)) {
2168 if (first)
2169 continue;
2170 if (pp->fmt == CMIT_FMT_SHORT)
2171 break;
2173 first = 0;
2175 strbuf_grow(sb, linelen + indent + 20);
2176 if (indent)
2177 pp_handle_indent(pp, sb, indent, line, linelen);
2178 else if (pp->expand_tabs_in_log)
2179 strbuf_add_tabexpand(sb, opt, pp->color,
2180 pp->expand_tabs_in_log, line,
2181 linelen);
2182 else {
2183 if (pp->fmt == CMIT_FMT_MBOXRD &&
2184 is_mboxrd_from(line, linelen))
2185 strbuf_addch(sb, '>');
2187 append_line_with_color(sb, opt, line, linelen,
2188 pp->color, GREP_CONTEXT_BODY,
2189 GREP_HEADER_FIELD_MAX);
2191 strbuf_addch(sb, '\n');
2195 void pretty_print_commit(struct pretty_print_context *pp,
2196 const struct commit *commit,
2197 struct strbuf *sb)
2199 unsigned long beginning_of_body;
2200 int indent = 4;
2201 const char *msg;
2202 const char *reencoded;
2203 const char *encoding;
2204 int need_8bit_cte = pp->need_8bit_cte;
2206 if (pp->fmt == CMIT_FMT_USERFORMAT) {
2207 repo_format_commit_message(the_repository, commit,
2208 user_format, sb, pp);
2209 return;
2212 encoding = get_log_output_encoding();
2213 msg = reencoded = repo_logmsg_reencode(the_repository, commit, NULL,
2214 encoding);
2216 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
2217 indent = 0;
2220 * We need to check and emit Content-type: to mark it
2221 * as 8-bit if we haven't done so.
2223 if (cmit_fmt_is_mail(pp->fmt) && need_8bit_cte == 0) {
2224 int i, ch, in_body;
2226 for (in_body = i = 0; (ch = msg[i]); i++) {
2227 if (!in_body) {
2228 /* author could be non 7-bit ASCII but
2229 * the log may be so; skip over the
2230 * header part first.
2232 if (ch == '\n' && msg[i+1] == '\n')
2233 in_body = 1;
2235 else if (non_ascii(ch)) {
2236 need_8bit_cte = 1;
2237 break;
2242 pp_header(pp, encoding, commit, &msg, sb);
2243 if (pp->fmt != CMIT_FMT_ONELINE && !pp->print_email_subject) {
2244 strbuf_addch(sb, '\n');
2247 /* Skip excess blank lines at the beginning of body, if any... */
2248 msg = skip_blank_lines(msg);
2250 /* These formats treat the title line specially. */
2251 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
2252 pp_title_line(pp, &msg, sb, encoding, need_8bit_cte);
2254 beginning_of_body = sb->len;
2255 if (pp->fmt != CMIT_FMT_ONELINE)
2256 pp_remainder(pp, &msg, sb, indent);
2257 strbuf_rtrim(sb);
2259 /* Make sure there is an EOLN for the non-oneline case */
2260 if (pp->fmt != CMIT_FMT_ONELINE)
2261 strbuf_addch(sb, '\n');
2264 * The caller may append additional body text in e-mail
2265 * format. Make sure we did not strip the blank line
2266 * between the header and the body.
2268 if (cmit_fmt_is_mail(pp->fmt) && sb->len <= beginning_of_body)
2269 strbuf_addch(sb, '\n');
2271 repo_unuse_commit_buffer(the_repository, commit, reencoded);
2274 void pp_commit_easy(enum cmit_fmt fmt, const struct commit *commit,
2275 struct strbuf *sb)
2277 struct pretty_print_context pp = {0};
2278 pp.fmt = fmt;
2279 pretty_print_commit(&pp, commit, sb);