Sync with 2.33.8
[git/debian.git] / pretty.c
blobe774b53bacda0bdbfbcb565544019fd49674de79
1 #include "cache.h"
2 #include "config.h"
3 #include "commit.h"
4 #include "utf8.h"
5 #include "diff.h"
6 #include "revision.h"
7 #include "string-list.h"
8 #include "mailmap.h"
9 #include "log-tree.h"
10 #include "notes.h"
11 #include "color.h"
12 #include "reflog-walk.h"
13 #include "gpg-interface.h"
14 #include "trailer.h"
15 #include "run-command.h"
18 * The limit for formatting directives, which enable the caller to append
19 * arbitrarily many bytes to the formatted buffer. This includes padding
20 * and wrapping formatters.
22 #define FORMATTING_LIMIT (16 * 1024)
24 static char *user_format;
25 static struct cmt_fmt_map {
26 const char *name;
27 enum cmit_fmt format;
28 int is_tformat;
29 int expand_tabs_in_log;
30 int is_alias;
31 enum date_mode_type default_date_mode_type;
32 const char *user_format;
33 } *commit_formats;
34 static size_t builtin_formats_len;
35 static size_t commit_formats_len;
36 static size_t commit_formats_alloc;
37 static struct cmt_fmt_map *find_commit_format(const char *sought);
39 int commit_format_is_empty(enum cmit_fmt fmt)
41 return fmt == CMIT_FMT_USERFORMAT && !*user_format;
44 static void save_user_format(struct rev_info *rev, const char *cp, int is_tformat)
46 free(user_format);
47 user_format = xstrdup(cp);
48 if (is_tformat)
49 rev->use_terminator = 1;
50 rev->commit_format = CMIT_FMT_USERFORMAT;
53 static int git_pretty_formats_config(const char *var, const char *value, void *cb)
55 struct cmt_fmt_map *commit_format = NULL;
56 const char *name;
57 const char *fmt;
58 int i;
60 if (!skip_prefix(var, "pretty.", &name))
61 return 0;
63 for (i = 0; i < builtin_formats_len; i++) {
64 if (!strcmp(commit_formats[i].name, name))
65 return 0;
68 for (i = builtin_formats_len; i < commit_formats_len; i++) {
69 if (!strcmp(commit_formats[i].name, name)) {
70 commit_format = &commit_formats[i];
71 break;
75 if (!commit_format) {
76 ALLOC_GROW(commit_formats, commit_formats_len+1,
77 commit_formats_alloc);
78 commit_format = &commit_formats[commit_formats_len];
79 memset(commit_format, 0, sizeof(*commit_format));
80 commit_formats_len++;
83 commit_format->name = xstrdup(name);
84 commit_format->format = CMIT_FMT_USERFORMAT;
85 if (git_config_string(&fmt, var, value))
86 return -1;
88 if (skip_prefix(fmt, "format:", &fmt))
89 commit_format->is_tformat = 0;
90 else if (skip_prefix(fmt, "tformat:", &fmt) || strchr(fmt, '%'))
91 commit_format->is_tformat = 1;
92 else
93 commit_format->is_alias = 1;
94 commit_format->user_format = fmt;
96 return 0;
99 static void setup_commit_formats(void)
101 struct cmt_fmt_map builtin_formats[] = {
102 { "raw", CMIT_FMT_RAW, 0, 0 },
103 { "medium", CMIT_FMT_MEDIUM, 0, 8 },
104 { "short", CMIT_FMT_SHORT, 0, 0 },
105 { "email", CMIT_FMT_EMAIL, 0, 0 },
106 { "mboxrd", CMIT_FMT_MBOXRD, 0, 0 },
107 { "fuller", CMIT_FMT_FULLER, 0, 8 },
108 { "full", CMIT_FMT_FULL, 0, 8 },
109 { "oneline", CMIT_FMT_ONELINE, 1, 0 },
110 { "reference", CMIT_FMT_USERFORMAT, 1, 0,
111 0, DATE_SHORT, "%C(auto)%h (%s, %ad)" },
113 * Please update $__git_log_pretty_formats in
114 * git-completion.bash when you add new formats.
117 commit_formats_len = ARRAY_SIZE(builtin_formats);
118 builtin_formats_len = commit_formats_len;
119 ALLOC_GROW(commit_formats, commit_formats_len, commit_formats_alloc);
120 COPY_ARRAY(commit_formats, builtin_formats,
121 ARRAY_SIZE(builtin_formats));
123 git_config(git_pretty_formats_config, NULL);
126 static struct cmt_fmt_map *find_commit_format_recursive(const char *sought,
127 const char *original,
128 int num_redirections)
130 struct cmt_fmt_map *found = NULL;
131 size_t found_match_len = 0;
132 int i;
134 if (num_redirections >= commit_formats_len)
135 die("invalid --pretty format: "
136 "'%s' references an alias which points to itself",
137 original);
139 for (i = 0; i < commit_formats_len; i++) {
140 size_t match_len;
142 if (!starts_with(commit_formats[i].name, sought))
143 continue;
145 match_len = strlen(commit_formats[i].name);
146 if (found == NULL || found_match_len > match_len) {
147 found = &commit_formats[i];
148 found_match_len = match_len;
152 if (found && found->is_alias) {
153 found = find_commit_format_recursive(found->user_format,
154 original,
155 num_redirections+1);
158 return found;
161 static struct cmt_fmt_map *find_commit_format(const char *sought)
163 if (!commit_formats)
164 setup_commit_formats();
166 return find_commit_format_recursive(sought, sought, 0);
169 void get_commit_format(const char *arg, struct rev_info *rev)
171 struct cmt_fmt_map *commit_format;
173 rev->use_terminator = 0;
174 if (!arg) {
175 rev->commit_format = CMIT_FMT_DEFAULT;
176 return;
178 if (skip_prefix(arg, "format:", &arg)) {
179 save_user_format(rev, arg, 0);
180 return;
183 if (!*arg || skip_prefix(arg, "tformat:", &arg) || strchr(arg, '%')) {
184 save_user_format(rev, arg, 1);
185 return;
188 commit_format = find_commit_format(arg);
189 if (!commit_format)
190 die("invalid --pretty format: %s", arg);
192 rev->commit_format = commit_format->format;
193 rev->use_terminator = commit_format->is_tformat;
194 rev->expand_tabs_in_log_default = commit_format->expand_tabs_in_log;
195 if (!rev->date_mode_explicit && commit_format->default_date_mode_type)
196 rev->date_mode.type = commit_format->default_date_mode_type;
197 if (commit_format->format == CMIT_FMT_USERFORMAT) {
198 save_user_format(rev, commit_format->user_format,
199 commit_format->is_tformat);
204 * Generic support for pretty-printing the header
206 static int get_one_line(const char *msg)
208 int ret = 0;
210 for (;;) {
211 char c = *msg++;
212 if (!c)
213 break;
214 ret++;
215 if (c == '\n')
216 break;
218 return ret;
221 /* High bit set, or ISO-2022-INT */
222 static int non_ascii(int ch)
224 return !isascii(ch) || ch == '\033';
227 int has_non_ascii(const char *s)
229 int ch;
230 if (!s)
231 return 0;
232 while ((ch = *s++) != '\0') {
233 if (non_ascii(ch))
234 return 1;
236 return 0;
239 static int is_rfc822_special(char ch)
241 switch (ch) {
242 case '(':
243 case ')':
244 case '<':
245 case '>':
246 case '[':
247 case ']':
248 case ':':
249 case ';':
250 case '@':
251 case ',':
252 case '.':
253 case '"':
254 case '\\':
255 return 1;
256 default:
257 return 0;
261 static int needs_rfc822_quoting(const char *s, int len)
263 int i;
264 for (i = 0; i < len; i++)
265 if (is_rfc822_special(s[i]))
266 return 1;
267 return 0;
270 static int last_line_length(struct strbuf *sb)
272 int i;
274 /* How many bytes are already used on the last line? */
275 for (i = sb->len - 1; i >= 0; i--)
276 if (sb->buf[i] == '\n')
277 break;
278 return sb->len - (i + 1);
281 static void add_rfc822_quoted(struct strbuf *out, const char *s, int len)
283 int i;
285 /* just a guess, we may have to also backslash-quote */
286 strbuf_grow(out, len + 2);
288 strbuf_addch(out, '"');
289 for (i = 0; i < len; i++) {
290 switch (s[i]) {
291 case '"':
292 case '\\':
293 strbuf_addch(out, '\\');
294 /* fall through */
295 default:
296 strbuf_addch(out, s[i]);
299 strbuf_addch(out, '"');
302 enum rfc2047_type {
303 RFC2047_SUBJECT,
304 RFC2047_ADDRESS
307 static int is_rfc2047_special(char ch, enum rfc2047_type type)
310 * rfc2047, section 4.2:
312 * 8-bit values which correspond to printable ASCII characters other
313 * than "=", "?", and "_" (underscore), MAY be represented as those
314 * characters. (But see section 5 for restrictions.) In
315 * particular, SPACE and TAB MUST NOT be represented as themselves
316 * within encoded words.
320 * rule out non-ASCII characters and non-printable characters (the
321 * non-ASCII check should be redundant as isprint() is not localized
322 * and only knows about ASCII, but be defensive about that)
324 if (non_ascii(ch) || !isprint(ch))
325 return 1;
328 * rule out special printable characters (' ' should be the only
329 * whitespace character considered printable, but be defensive and use
330 * isspace())
332 if (isspace(ch) || ch == '=' || ch == '?' || ch == '_')
333 return 1;
336 * rfc2047, section 5.3:
338 * As a replacement for a 'word' entity within a 'phrase', for example,
339 * one that precedes an address in a From, To, or Cc header. The ABNF
340 * definition for 'phrase' from RFC 822 thus becomes:
342 * phrase = 1*( encoded-word / word )
344 * In this case the set of characters that may be used in a "Q"-encoded
345 * 'encoded-word' is restricted to: <upper and lower case ASCII
346 * letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
347 * (underscore, ASCII 95.)>. An 'encoded-word' that appears within a
348 * 'phrase' MUST be separated from any adjacent 'word', 'text' or
349 * 'special' by 'linear-white-space'.
352 if (type != RFC2047_ADDRESS)
353 return 0;
355 /* '=' and '_' are special cases and have been checked above */
356 return !(isalnum(ch) || ch == '!' || ch == '*' || ch == '+' || ch == '-' || ch == '/');
359 static int needs_rfc2047_encoding(const char *line, int len)
361 int i;
363 for (i = 0; i < len; i++) {
364 int ch = line[i];
365 if (non_ascii(ch) || ch == '\n')
366 return 1;
367 if ((i + 1 < len) && (ch == '=' && line[i+1] == '?'))
368 return 1;
371 return 0;
374 static void add_rfc2047(struct strbuf *sb, const char *line, size_t len,
375 const char *encoding, enum rfc2047_type type)
377 static const int max_encoded_length = 76; /* per rfc2047 */
378 int i;
379 int line_len = last_line_length(sb);
381 strbuf_grow(sb, len * 3 + strlen(encoding) + 100);
382 strbuf_addf(sb, "=?%s?q?", encoding);
383 line_len += strlen(encoding) + 5; /* 5 for =??q? */
385 while (len) {
387 * RFC 2047, section 5 (3):
389 * Each 'encoded-word' MUST represent an integral number of
390 * characters. A multi-octet character may not be split across
391 * adjacent 'encoded- word's.
393 const unsigned char *p = (const unsigned char *)line;
394 int chrlen = mbs_chrlen(&line, &len, encoding);
395 int is_special = (chrlen > 1) || is_rfc2047_special(*p, type);
397 /* "=%02X" * chrlen, or the byte itself */
398 const char *encoded_fmt = is_special ? "=%02X" : "%c";
399 int encoded_len = is_special ? 3 * chrlen : 1;
402 * According to RFC 2047, we could encode the special character
403 * ' ' (space) with '_' (underscore) for readability. But many
404 * programs do not understand this and just leave the
405 * underscore in place. Thus, we do nothing special here, which
406 * causes ' ' to be encoded as '=20', avoiding this problem.
409 if (line_len + encoded_len + 2 > max_encoded_length) {
410 /* It won't fit with trailing "?=" --- break the line */
411 strbuf_addf(sb, "?=\n =?%s?q?", encoding);
412 line_len = strlen(encoding) + 5 + 1; /* =??q? plus SP */
415 for (i = 0; i < chrlen; i++)
416 strbuf_addf(sb, encoded_fmt, p[i]);
417 line_len += encoded_len;
419 strbuf_addstr(sb, "?=");
422 const char *show_ident_date(const struct ident_split *ident,
423 const struct date_mode *mode)
425 timestamp_t date = 0;
426 long tz = 0;
428 if (ident->date_begin && ident->date_end)
429 date = parse_timestamp(ident->date_begin, NULL, 10);
430 if (date_overflows(date))
431 date = 0;
432 else {
433 if (ident->tz_begin && ident->tz_end)
434 tz = strtol(ident->tz_begin, NULL, 10);
435 if (tz >= INT_MAX || tz <= INT_MIN)
436 tz = 0;
438 return show_date(date, tz, mode);
441 static inline void strbuf_add_with_color(struct strbuf *sb, const char *color,
442 const char *buf, size_t buflen)
444 strbuf_addstr(sb, color);
445 strbuf_add(sb, buf, buflen);
446 if (*color)
447 strbuf_addstr(sb, GIT_COLOR_RESET);
450 static void append_line_with_color(struct strbuf *sb, struct grep_opt *opt,
451 const char *line, size_t linelen,
452 int color, enum grep_context ctx,
453 enum grep_header_field field)
455 const char *buf, *eol, *line_color, *match_color;
456 regmatch_t match;
457 int eflags = 0;
459 buf = line;
460 eol = buf + linelen;
462 if (!opt || !want_color(color) || opt->invert)
463 goto end;
465 line_color = opt->colors[GREP_COLOR_SELECTED];
466 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
468 while (grep_next_match(opt, buf, eol, ctx, &match, field, eflags)) {
469 if (match.rm_so == match.rm_eo)
470 break;
472 strbuf_add_with_color(sb, line_color, buf, match.rm_so);
473 strbuf_add_with_color(sb, match_color, buf + match.rm_so,
474 match.rm_eo - match.rm_so);
475 buf += match.rm_eo;
476 eflags = REG_NOTBOL;
479 if (eflags)
480 strbuf_add_with_color(sb, line_color, buf, eol - buf);
481 else {
482 end:
483 strbuf_add(sb, buf, eol - buf);
487 void pp_user_info(struct pretty_print_context *pp,
488 const char *what, struct strbuf *sb,
489 const char *line, const char *encoding)
491 struct ident_split ident;
492 char *line_end;
493 const char *mailbuf, *namebuf;
494 size_t namelen, maillen;
495 int max_length = 78; /* per rfc2822 */
497 if (pp->fmt == CMIT_FMT_ONELINE)
498 return;
500 line_end = strchrnul(line, '\n');
501 if (split_ident_line(&ident, line, line_end - line))
502 return;
504 mailbuf = ident.mail_begin;
505 maillen = ident.mail_end - ident.mail_begin;
506 namebuf = ident.name_begin;
507 namelen = ident.name_end - ident.name_begin;
509 if (pp->mailmap)
510 map_user(pp->mailmap, &mailbuf, &maillen, &namebuf, &namelen);
512 if (cmit_fmt_is_mail(pp->fmt)) {
513 if (pp->from_ident && ident_cmp(pp->from_ident, &ident)) {
514 struct strbuf buf = STRBUF_INIT;
516 strbuf_addstr(&buf, "From: ");
517 strbuf_add(&buf, namebuf, namelen);
518 strbuf_addstr(&buf, " <");
519 strbuf_add(&buf, mailbuf, maillen);
520 strbuf_addstr(&buf, ">\n");
521 string_list_append(&pp->in_body_headers,
522 strbuf_detach(&buf, NULL));
524 mailbuf = pp->from_ident->mail_begin;
525 maillen = pp->from_ident->mail_end - mailbuf;
526 namebuf = pp->from_ident->name_begin;
527 namelen = pp->from_ident->name_end - namebuf;
530 strbuf_addstr(sb, "From: ");
531 if (pp->encode_email_headers &&
532 needs_rfc2047_encoding(namebuf, namelen)) {
533 add_rfc2047(sb, namebuf, namelen,
534 encoding, RFC2047_ADDRESS);
535 max_length = 76; /* per rfc2047 */
536 } else if (needs_rfc822_quoting(namebuf, namelen)) {
537 struct strbuf quoted = STRBUF_INIT;
538 add_rfc822_quoted(&quoted, namebuf, namelen);
539 strbuf_add_wrapped_bytes(sb, quoted.buf, quoted.len,
540 -6, 1, max_length);
541 strbuf_release(&quoted);
542 } else {
543 strbuf_add_wrapped_bytes(sb, namebuf, namelen,
544 -6, 1, max_length);
547 if (max_length <
548 last_line_length(sb) + strlen(" <") + maillen + strlen(">"))
549 strbuf_addch(sb, '\n');
550 strbuf_addf(sb, " <%.*s>\n", (int)maillen, mailbuf);
551 } else {
552 struct strbuf id = STRBUF_INIT;
553 enum grep_header_field field = GREP_HEADER_FIELD_MAX;
554 struct grep_opt *opt = pp->rev ? &pp->rev->grep_filter : NULL;
556 if (!strcmp(what, "Author"))
557 field = GREP_HEADER_AUTHOR;
558 else if (!strcmp(what, "Commit"))
559 field = GREP_HEADER_COMMITTER;
561 strbuf_addf(sb, "%s: ", what);
562 if (pp->fmt == CMIT_FMT_FULLER)
563 strbuf_addchars(sb, ' ', 4);
565 strbuf_addf(&id, "%.*s <%.*s>", (int)namelen, namebuf,
566 (int)maillen, mailbuf);
568 append_line_with_color(sb, opt, id.buf, id.len, pp->color,
569 GREP_CONTEXT_HEAD, field);
570 strbuf_addch(sb, '\n');
571 strbuf_release(&id);
574 switch (pp->fmt) {
575 case CMIT_FMT_MEDIUM:
576 strbuf_addf(sb, "Date: %s\n",
577 show_ident_date(&ident, &pp->date_mode));
578 break;
579 case CMIT_FMT_EMAIL:
580 case CMIT_FMT_MBOXRD:
581 strbuf_addf(sb, "Date: %s\n",
582 show_ident_date(&ident, DATE_MODE(RFC2822)));
583 break;
584 case CMIT_FMT_FULLER:
585 strbuf_addf(sb, "%sDate: %s\n", what,
586 show_ident_date(&ident, &pp->date_mode));
587 break;
588 default:
589 /* notin' */
590 break;
594 static int is_blank_line(const char *line, int *len_p)
596 int len = *len_p;
597 while (len && isspace(line[len - 1]))
598 len--;
599 *len_p = len;
600 return !len;
603 const char *skip_blank_lines(const char *msg)
605 for (;;) {
606 int linelen = get_one_line(msg);
607 int ll = linelen;
608 if (!linelen)
609 break;
610 if (!is_blank_line(msg, &ll))
611 break;
612 msg += linelen;
614 return msg;
617 static void add_merge_info(const struct pretty_print_context *pp,
618 struct strbuf *sb, const struct commit *commit)
620 struct commit_list *parent = commit->parents;
622 if ((pp->fmt == CMIT_FMT_ONELINE) || (cmit_fmt_is_mail(pp->fmt)) ||
623 !parent || !parent->next)
624 return;
626 strbuf_addstr(sb, "Merge:");
628 while (parent) {
629 struct object_id *oidp = &parent->item->object.oid;
630 strbuf_addch(sb, ' ');
631 if (pp->abbrev)
632 strbuf_add_unique_abbrev(sb, oidp, pp->abbrev);
633 else
634 strbuf_addstr(sb, oid_to_hex(oidp));
635 parent = parent->next;
637 strbuf_addch(sb, '\n');
640 static char *get_header(const char *msg, const char *key)
642 size_t len;
643 const char *v = find_commit_header(msg, key, &len);
644 return v ? xmemdupz(v, len) : NULL;
647 static char *replace_encoding_header(char *buf, const char *encoding)
649 struct strbuf tmp = STRBUF_INIT;
650 size_t start, len;
651 char *cp = buf;
653 /* guess if there is an encoding header before a \n\n */
654 while (!starts_with(cp, "encoding ")) {
655 cp = strchr(cp, '\n');
656 if (!cp || *++cp == '\n')
657 return buf;
659 start = cp - buf;
660 cp = strchr(cp, '\n');
661 if (!cp)
662 return buf; /* should not happen but be defensive */
663 len = cp + 1 - (buf + start);
665 strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
666 if (is_encoding_utf8(encoding)) {
667 /* we have re-coded to UTF-8; drop the header */
668 strbuf_remove(&tmp, start, len);
669 } else {
670 /* just replaces XXXX in 'encoding XXXX\n' */
671 strbuf_splice(&tmp, start + strlen("encoding "),
672 len - strlen("encoding \n"),
673 encoding, strlen(encoding));
675 return strbuf_detach(&tmp, NULL);
678 const char *repo_logmsg_reencode(struct repository *r,
679 const struct commit *commit,
680 char **commit_encoding,
681 const char *output_encoding)
683 static const char *utf8 = "UTF-8";
684 const char *use_encoding;
685 char *encoding;
686 const char *msg = repo_get_commit_buffer(r, commit, NULL);
687 char *out;
689 if (!output_encoding || !*output_encoding) {
690 if (commit_encoding)
691 *commit_encoding = get_header(msg, "encoding");
692 return msg;
694 encoding = get_header(msg, "encoding");
695 if (commit_encoding)
696 *commit_encoding = encoding;
697 use_encoding = encoding ? encoding : utf8;
698 if (same_encoding(use_encoding, output_encoding)) {
700 * No encoding work to be done. If we have no encoding header
701 * at all, then there's nothing to do, and we can return the
702 * message verbatim (whether newly allocated or not).
704 if (!encoding)
705 return msg;
708 * Otherwise, we still want to munge the encoding header in the
709 * result, which will be done by modifying the buffer. If we
710 * are using a fresh copy, we can reuse it. But if we are using
711 * the cached copy from get_commit_buffer, we need to duplicate it
712 * to avoid munging the cached copy.
714 if (msg == get_cached_commit_buffer(r, commit, NULL))
715 out = xstrdup(msg);
716 else
717 out = (char *)msg;
719 else {
721 * There's actual encoding work to do. Do the reencoding, which
722 * still leaves the header to be replaced in the next step. At
723 * this point, we are done with msg. If we allocated a fresh
724 * copy, we can free it.
726 out = reencode_string(msg, output_encoding, use_encoding);
727 if (out)
728 repo_unuse_commit_buffer(r, commit, msg);
732 * This replacement actually consumes the buffer we hand it, so we do
733 * not have to worry about freeing the old "out" here.
735 if (out)
736 out = replace_encoding_header(out, output_encoding);
738 if (!commit_encoding)
739 free(encoding);
741 * If the re-encoding failed, out might be NULL here; in that
742 * case we just return the commit message verbatim.
744 return out ? out : msg;
747 static int mailmap_name(const char **email, size_t *email_len,
748 const char **name, size_t *name_len)
750 static struct string_list *mail_map;
751 if (!mail_map) {
752 CALLOC_ARRAY(mail_map, 1);
753 read_mailmap(mail_map);
755 return mail_map->nr && map_user(mail_map, email, email_len, name, name_len);
758 static size_t format_person_part(struct strbuf *sb, char part,
759 const char *msg, int len,
760 const struct date_mode *dmode)
762 /* currently all placeholders have same length */
763 const int placeholder_len = 2;
764 struct ident_split s;
765 const char *name, *mail;
766 size_t maillen, namelen;
768 if (split_ident_line(&s, msg, len) < 0)
769 goto skip;
771 name = s.name_begin;
772 namelen = s.name_end - s.name_begin;
773 mail = s.mail_begin;
774 maillen = s.mail_end - s.mail_begin;
776 if (part == 'N' || part == 'E' || part == 'L') /* mailmap lookup */
777 mailmap_name(&mail, &maillen, &name, &namelen);
778 if (part == 'n' || part == 'N') { /* name */
779 strbuf_add(sb, name, namelen);
780 return placeholder_len;
782 if (part == 'e' || part == 'E') { /* email */
783 strbuf_add(sb, mail, maillen);
784 return placeholder_len;
786 if (part == 'l' || part == 'L') { /* local-part */
787 const char *at = memchr(mail, '@', maillen);
788 if (at)
789 maillen = at - mail;
790 strbuf_add(sb, mail, maillen);
791 return placeholder_len;
794 if (!s.date_begin)
795 goto skip;
797 if (part == 't') { /* date, UNIX timestamp */
798 strbuf_add(sb, s.date_begin, s.date_end - s.date_begin);
799 return placeholder_len;
802 switch (part) {
803 case 'd': /* date */
804 strbuf_addstr(sb, show_ident_date(&s, dmode));
805 return placeholder_len;
806 case 'D': /* date, RFC2822 style */
807 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RFC2822)));
808 return placeholder_len;
809 case 'r': /* date, relative */
810 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RELATIVE)));
811 return placeholder_len;
812 case 'i': /* date, ISO 8601-like */
813 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601)));
814 return placeholder_len;
815 case 'I': /* date, ISO 8601 strict */
816 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601_STRICT)));
817 return placeholder_len;
818 case 'h': /* date, human */
819 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(HUMAN)));
820 return placeholder_len;
821 case 's':
822 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(SHORT)));
823 return placeholder_len;
826 skip:
828 * reading from either a bogus commit, or a reflog entry with
829 * %gn, %ge, etc.; 'sb' cannot be updated, but we still need
830 * to compute a valid return value.
832 if (part == 'n' || part == 'e' || part == 't' || part == 'd'
833 || part == 'D' || part == 'r' || part == 'i')
834 return placeholder_len;
836 return 0; /* unknown placeholder */
839 struct chunk {
840 size_t off;
841 size_t len;
844 enum flush_type {
845 no_flush,
846 flush_right,
847 flush_left,
848 flush_left_and_steal,
849 flush_both
852 enum trunc_type {
853 trunc_none,
854 trunc_left,
855 trunc_middle,
856 trunc_right
859 struct format_commit_context {
860 struct repository *repository;
861 const struct commit *commit;
862 const struct pretty_print_context *pretty_ctx;
863 unsigned commit_header_parsed:1;
864 unsigned commit_message_parsed:1;
865 struct signature_check signature_check;
866 enum flush_type flush_type;
867 enum trunc_type truncate;
868 const char *message;
869 char *commit_encoding;
870 size_t width, indent1, indent2;
871 int auto_color;
872 int padding;
874 /* These offsets are relative to the start of the commit message. */
875 struct chunk author;
876 struct chunk committer;
877 size_t message_off;
878 size_t subject_off;
879 size_t body_off;
881 /* The following ones are relative to the result struct strbuf. */
882 size_t wrap_start;
885 static void parse_commit_header(struct format_commit_context *context)
887 const char *msg = context->message;
888 int i;
890 for (i = 0; msg[i]; i++) {
891 const char *name;
892 int eol;
893 for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
894 ; /* do nothing */
896 if (i == eol) {
897 break;
898 } else if (skip_prefix(msg + i, "author ", &name)) {
899 context->author.off = name - msg;
900 context->author.len = msg + eol - name;
901 } else if (skip_prefix(msg + i, "committer ", &name)) {
902 context->committer.off = name - msg;
903 context->committer.len = msg + eol - name;
905 i = eol;
907 context->message_off = i;
908 context->commit_header_parsed = 1;
911 static int istitlechar(char c)
913 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
914 (c >= '0' && c <= '9') || c == '.' || c == '_';
917 void format_sanitized_subject(struct strbuf *sb, const char *msg, size_t len)
919 size_t trimlen;
920 size_t start_len = sb->len;
921 int space = 2;
922 int i;
924 for (i = 0; i < len; i++) {
925 if (istitlechar(msg[i])) {
926 if (space == 1)
927 strbuf_addch(sb, '-');
928 space = 0;
929 strbuf_addch(sb, msg[i]);
930 if (msg[i] == '.')
931 while (msg[i+1] == '.')
932 i++;
933 } else
934 space |= 1;
937 /* trim any trailing '.' or '-' characters */
938 trimlen = 0;
939 while (sb->len - trimlen > start_len &&
940 (sb->buf[sb->len - 1 - trimlen] == '.'
941 || sb->buf[sb->len - 1 - trimlen] == '-'))
942 trimlen++;
943 strbuf_remove(sb, sb->len - trimlen, trimlen);
946 const char *format_subject(struct strbuf *sb, const char *msg,
947 const char *line_separator)
949 int first = 1;
951 for (;;) {
952 const char *line = msg;
953 int linelen = get_one_line(line);
955 msg += linelen;
956 if (!linelen || is_blank_line(line, &linelen))
957 break;
959 if (!sb)
960 continue;
961 strbuf_grow(sb, linelen + 2);
962 if (!first)
963 strbuf_addstr(sb, line_separator);
964 strbuf_add(sb, line, linelen);
965 first = 0;
967 return msg;
970 static void parse_commit_message(struct format_commit_context *c)
972 const char *msg = c->message + c->message_off;
973 const char *start = c->message;
975 msg = skip_blank_lines(msg);
976 c->subject_off = msg - start;
978 msg = format_subject(NULL, msg, NULL);
979 msg = skip_blank_lines(msg);
980 c->body_off = msg - start;
982 c->commit_message_parsed = 1;
985 static void strbuf_wrap(struct strbuf *sb, size_t pos,
986 size_t width, size_t indent1, size_t indent2)
988 struct strbuf tmp = STRBUF_INIT;
990 if (pos)
991 strbuf_add(&tmp, sb->buf, pos);
992 strbuf_add_wrapped_text(&tmp, sb->buf + pos,
993 cast_size_t_to_int(indent1),
994 cast_size_t_to_int(indent2),
995 cast_size_t_to_int(width));
996 strbuf_swap(&tmp, sb);
997 strbuf_release(&tmp);
1000 static void rewrap_message_tail(struct strbuf *sb,
1001 struct format_commit_context *c,
1002 size_t new_width, size_t new_indent1,
1003 size_t new_indent2)
1005 if (c->width == new_width && c->indent1 == new_indent1 &&
1006 c->indent2 == new_indent2)
1007 return;
1008 if (c->wrap_start < sb->len)
1009 strbuf_wrap(sb, c->wrap_start, c->width, c->indent1, c->indent2);
1010 c->wrap_start = sb->len;
1011 c->width = new_width;
1012 c->indent1 = new_indent1;
1013 c->indent2 = new_indent2;
1016 static int format_reflog_person(struct strbuf *sb,
1017 char part,
1018 struct reflog_walk_info *log,
1019 const struct date_mode *dmode)
1021 const char *ident;
1023 if (!log)
1024 return 2;
1026 ident = get_reflog_ident(log);
1027 if (!ident)
1028 return 2;
1030 return format_person_part(sb, part, ident, strlen(ident), dmode);
1033 static size_t parse_color(struct strbuf *sb, /* in UTF-8 */
1034 const char *placeholder,
1035 struct format_commit_context *c)
1037 const char *rest = placeholder;
1038 const char *basic_color = NULL;
1040 if (placeholder[1] == '(') {
1041 const char *begin = placeholder + 2;
1042 const char *end = strchr(begin, ')');
1043 char color[COLOR_MAXLEN];
1045 if (!end)
1046 return 0;
1048 if (skip_prefix(begin, "auto,", &begin)) {
1049 if (!want_color(c->pretty_ctx->color))
1050 return end - placeholder + 1;
1051 } else if (skip_prefix(begin, "always,", &begin)) {
1052 /* nothing to do; we do not respect want_color at all */
1053 } else {
1054 /* the default is the same as "auto" */
1055 if (!want_color(c->pretty_ctx->color))
1056 return end - placeholder + 1;
1059 if (color_parse_mem(begin, end - begin, color) < 0)
1060 die(_("unable to parse --pretty format"));
1061 strbuf_addstr(sb, color);
1062 return end - placeholder + 1;
1066 * We handle things like "%C(red)" above; for historical reasons, there
1067 * are a few colors that can be specified without parentheses (and
1068 * they cannot support things like "auto" or "always" at all).
1070 if (skip_prefix(placeholder + 1, "red", &rest))
1071 basic_color = GIT_COLOR_RED;
1072 else if (skip_prefix(placeholder + 1, "green", &rest))
1073 basic_color = GIT_COLOR_GREEN;
1074 else if (skip_prefix(placeholder + 1, "blue", &rest))
1075 basic_color = GIT_COLOR_BLUE;
1076 else if (skip_prefix(placeholder + 1, "reset", &rest))
1077 basic_color = GIT_COLOR_RESET;
1079 if (basic_color && want_color(c->pretty_ctx->color))
1080 strbuf_addstr(sb, basic_color);
1082 return rest - placeholder;
1085 static size_t parse_padding_placeholder(const char *placeholder,
1086 struct format_commit_context *c)
1088 const char *ch = placeholder;
1089 enum flush_type flush_type;
1090 int to_column = 0;
1092 switch (*ch++) {
1093 case '<':
1094 flush_type = flush_right;
1095 break;
1096 case '>':
1097 if (*ch == '<') {
1098 flush_type = flush_both;
1099 ch++;
1100 } else if (*ch == '>') {
1101 flush_type = flush_left_and_steal;
1102 ch++;
1103 } else
1104 flush_type = flush_left;
1105 break;
1106 default:
1107 return 0;
1110 /* the next value means "wide enough to that column" */
1111 if (*ch == '|') {
1112 to_column = 1;
1113 ch++;
1116 if (*ch == '(') {
1117 const char *start = ch + 1;
1118 const char *end = start + strcspn(start, ",)");
1119 char *next;
1120 int width;
1121 if (!*end || end == start)
1122 return 0;
1123 width = strtol(start, &next, 10);
1126 * We need to limit the amount of padding, or otherwise this
1127 * would allow the user to pad the buffer by arbitrarily many
1128 * bytes and thus cause resource exhaustion.
1130 if (width < -FORMATTING_LIMIT || width > FORMATTING_LIMIT)
1131 return 0;
1133 if (next == start || width == 0)
1134 return 0;
1135 if (width < 0) {
1136 if (to_column)
1137 width += term_columns();
1138 if (width < 0)
1139 return 0;
1141 c->padding = to_column ? -width : width;
1142 c->flush_type = flush_type;
1144 if (*end == ',') {
1145 start = end + 1;
1146 end = strchr(start, ')');
1147 if (!end || end == start)
1148 return 0;
1149 if (starts_with(start, "trunc)"))
1150 c->truncate = trunc_right;
1151 else if (starts_with(start, "ltrunc)"))
1152 c->truncate = trunc_left;
1153 else if (starts_with(start, "mtrunc)"))
1154 c->truncate = trunc_middle;
1155 else
1156 return 0;
1157 } else
1158 c->truncate = trunc_none;
1160 return end - placeholder + 1;
1162 return 0;
1165 static int match_placeholder_arg_value(const char *to_parse, const char *candidate,
1166 const char **end, const char **valuestart,
1167 size_t *valuelen)
1169 const char *p;
1171 if (!(skip_prefix(to_parse, candidate, &p)))
1172 return 0;
1173 if (valuestart) {
1174 if (*p == '=') {
1175 *valuestart = p + 1;
1176 *valuelen = strcspn(*valuestart, ",)");
1177 p = *valuestart + *valuelen;
1178 } else {
1179 if (*p != ',' && *p != ')')
1180 return 0;
1181 *valuestart = NULL;
1182 *valuelen = 0;
1185 if (*p == ',') {
1186 *end = p + 1;
1187 return 1;
1189 if (*p == ')') {
1190 *end = p;
1191 return 1;
1193 return 0;
1196 static int match_placeholder_bool_arg(const char *to_parse, const char *candidate,
1197 const char **end, int *val)
1199 const char *argval;
1200 char *strval;
1201 size_t arglen;
1202 int v;
1204 if (!match_placeholder_arg_value(to_parse, candidate, end, &argval, &arglen))
1205 return 0;
1207 if (!argval) {
1208 *val = 1;
1209 return 1;
1212 strval = xstrndup(argval, arglen);
1213 v = git_parse_maybe_bool(strval);
1214 free(strval);
1216 if (v == -1)
1217 return 0;
1219 *val = v;
1221 return 1;
1224 static int format_trailer_match_cb(const struct strbuf *key, void *ud)
1226 const struct string_list *list = ud;
1227 const struct string_list_item *item;
1229 for_each_string_list_item (item, list) {
1230 if (key->len == (uintptr_t)item->util &&
1231 !strncasecmp(item->string, key->buf, key->len))
1232 return 1;
1234 return 0;
1237 int format_set_trailers_options(struct process_trailer_options *opts,
1238 struct string_list *filter_list,
1239 struct strbuf *sepbuf,
1240 struct strbuf *kvsepbuf,
1241 const char **arg,
1242 char **invalid_arg)
1244 for (;;) {
1245 const char *argval;
1246 size_t arglen;
1248 if (**arg == ')')
1249 break;
1251 if (match_placeholder_arg_value(*arg, "key", arg, &argval, &arglen)) {
1252 uintptr_t len = arglen;
1254 if (!argval)
1255 return -1;
1257 if (len && argval[len - 1] == ':')
1258 len--;
1259 string_list_append(filter_list, argval)->util = (char *)len;
1261 opts->filter = format_trailer_match_cb;
1262 opts->filter_data = filter_list;
1263 opts->only_trailers = 1;
1264 } else if (match_placeholder_arg_value(*arg, "separator", arg, &argval, &arglen)) {
1265 char *fmt;
1267 strbuf_reset(sepbuf);
1268 fmt = xstrndup(argval, arglen);
1269 strbuf_expand(sepbuf, fmt, strbuf_expand_literal_cb, NULL);
1270 free(fmt);
1271 opts->separator = sepbuf;
1272 } else if (match_placeholder_arg_value(*arg, "key_value_separator", arg, &argval, &arglen)) {
1273 char *fmt;
1275 strbuf_reset(kvsepbuf);
1276 fmt = xstrndup(argval, arglen);
1277 strbuf_expand(kvsepbuf, fmt, strbuf_expand_literal_cb, NULL);
1278 free(fmt);
1279 opts->key_value_separator = kvsepbuf;
1280 } else if (!match_placeholder_bool_arg(*arg, "only", arg, &opts->only_trailers) &&
1281 !match_placeholder_bool_arg(*arg, "unfold", arg, &opts->unfold) &&
1282 !match_placeholder_bool_arg(*arg, "keyonly", arg, &opts->key_only) &&
1283 !match_placeholder_bool_arg(*arg, "valueonly", arg, &opts->value_only)) {
1284 if (invalid_arg) {
1285 size_t len = strcspn(*arg, ",)");
1286 *invalid_arg = xstrndup(*arg, len);
1288 return -1;
1291 return 0;
1294 static size_t parse_describe_args(const char *start, struct strvec *args)
1296 const char *options[] = { "match", "exclude" };
1297 const char *arg = start;
1299 for (;;) {
1300 const char *matched = NULL;
1301 const char *argval;
1302 size_t arglen = 0;
1303 int i;
1305 for (i = 0; i < ARRAY_SIZE(options); i++) {
1306 if (match_placeholder_arg_value(arg, options[i], &arg,
1307 &argval, &arglen)) {
1308 matched = options[i];
1309 break;
1312 if (!matched)
1313 break;
1315 if (!arglen)
1316 return 0;
1317 strvec_pushf(args, "--%s=%.*s", matched, (int)arglen, argval);
1319 return arg - start;
1322 static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
1323 const char *placeholder,
1324 void *context)
1326 struct format_commit_context *c = context;
1327 const struct commit *commit = c->commit;
1328 const char *msg = c->message;
1329 struct commit_list *p;
1330 const char *arg, *eol;
1331 size_t res;
1332 char **slot;
1334 /* these are independent of the commit */
1335 res = strbuf_expand_literal_cb(sb, placeholder, NULL);
1336 if (res)
1337 return res;
1339 switch (placeholder[0]) {
1340 case 'C':
1341 if (starts_with(placeholder + 1, "(auto)")) {
1342 c->auto_color = want_color(c->pretty_ctx->color);
1343 if (c->auto_color && sb->len)
1344 strbuf_addstr(sb, GIT_COLOR_RESET);
1345 return 7; /* consumed 7 bytes, "C(auto)" */
1346 } else {
1347 int ret = parse_color(sb, placeholder, c);
1348 if (ret)
1349 c->auto_color = 0;
1351 * Otherwise, we decided to treat %C<unknown>
1352 * as a literal string, and the previous
1353 * %C(auto) is still valid.
1355 return ret;
1357 case 'w':
1358 if (placeholder[1] == '(') {
1359 unsigned long width = 0, indent1 = 0, indent2 = 0;
1360 char *next;
1361 const char *start = placeholder + 2;
1362 const char *end = strchr(start, ')');
1363 if (!end)
1364 return 0;
1365 if (end > start) {
1366 width = strtoul(start, &next, 10);
1367 if (*next == ',') {
1368 indent1 = strtoul(next + 1, &next, 10);
1369 if (*next == ',') {
1370 indent2 = strtoul(next + 1,
1371 &next, 10);
1374 if (*next != ')')
1375 return 0;
1379 * We need to limit the format here as it allows the
1380 * user to prepend arbitrarily many bytes to the buffer
1381 * when rewrapping.
1383 if (width > FORMATTING_LIMIT ||
1384 indent1 > FORMATTING_LIMIT ||
1385 indent2 > FORMATTING_LIMIT)
1386 return 0;
1387 rewrap_message_tail(sb, c, width, indent1, indent2);
1388 return end - placeholder + 1;
1389 } else
1390 return 0;
1392 case '<':
1393 case '>':
1394 return parse_padding_placeholder(placeholder, c);
1397 if (skip_prefix(placeholder, "(describe", &arg)) {
1398 struct child_process cmd = CHILD_PROCESS_INIT;
1399 struct strbuf out = STRBUF_INIT;
1400 struct strbuf err = STRBUF_INIT;
1401 struct pretty_print_describe_status *describe_status;
1403 describe_status = c->pretty_ctx->describe_status;
1404 if (describe_status) {
1405 if (!describe_status->max_invocations)
1406 return 0;
1407 describe_status->max_invocations--;
1410 cmd.git_cmd = 1;
1411 strvec_push(&cmd.args, "describe");
1413 if (*arg == ':') {
1414 arg++;
1415 arg += parse_describe_args(arg, &cmd.args);
1418 if (*arg != ')') {
1419 child_process_clear(&cmd);
1420 return 0;
1423 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1424 pipe_command(&cmd, NULL, 0, &out, 0, &err, 0);
1425 strbuf_rtrim(&out);
1426 strbuf_addbuf(sb, &out);
1427 strbuf_release(&out);
1428 strbuf_release(&err);
1429 return arg - placeholder + 1;
1432 /* these depend on the commit */
1433 if (!commit->object.parsed)
1434 parse_object(the_repository, &commit->object.oid);
1436 switch (placeholder[0]) {
1437 case 'H': /* commit hash */
1438 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1439 strbuf_addstr(sb, oid_to_hex(&commit->object.oid));
1440 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1441 return 1;
1442 case 'h': /* abbreviated commit hash */
1443 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1444 strbuf_add_unique_abbrev(sb, &commit->object.oid,
1445 c->pretty_ctx->abbrev);
1446 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1447 return 1;
1448 case 'T': /* tree hash */
1449 strbuf_addstr(sb, oid_to_hex(get_commit_tree_oid(commit)));
1450 return 1;
1451 case 't': /* abbreviated tree hash */
1452 strbuf_add_unique_abbrev(sb,
1453 get_commit_tree_oid(commit),
1454 c->pretty_ctx->abbrev);
1455 return 1;
1456 case 'P': /* parent hashes */
1457 for (p = commit->parents; p; p = p->next) {
1458 if (p != commit->parents)
1459 strbuf_addch(sb, ' ');
1460 strbuf_addstr(sb, oid_to_hex(&p->item->object.oid));
1462 return 1;
1463 case 'p': /* abbreviated parent hashes */
1464 for (p = commit->parents; p; p = p->next) {
1465 if (p != commit->parents)
1466 strbuf_addch(sb, ' ');
1467 strbuf_add_unique_abbrev(sb, &p->item->object.oid,
1468 c->pretty_ctx->abbrev);
1470 return 1;
1471 case 'm': /* left/right/bottom */
1472 strbuf_addstr(sb, get_revision_mark(NULL, commit));
1473 return 1;
1474 case 'd':
1475 format_decorations(sb, commit, c->auto_color);
1476 return 1;
1477 case 'D':
1478 format_decorations_extended(sb, commit, c->auto_color, "", ", ", "");
1479 return 1;
1480 case 'S': /* tag/branch like --source */
1481 if (!(c->pretty_ctx->rev && c->pretty_ctx->rev->sources))
1482 return 0;
1483 slot = revision_sources_at(c->pretty_ctx->rev->sources, commit);
1484 if (!(slot && *slot))
1485 return 0;
1486 strbuf_addstr(sb, *slot);
1487 return 1;
1488 case 'g': /* reflog info */
1489 switch(placeholder[1]) {
1490 case 'd': /* reflog selector */
1491 case 'D':
1492 if (c->pretty_ctx->reflog_info)
1493 get_reflog_selector(sb,
1494 c->pretty_ctx->reflog_info,
1495 &c->pretty_ctx->date_mode,
1496 c->pretty_ctx->date_mode_explicit,
1497 (placeholder[1] == 'd'));
1498 return 2;
1499 case 's': /* reflog message */
1500 if (c->pretty_ctx->reflog_info)
1501 get_reflog_message(sb, c->pretty_ctx->reflog_info);
1502 return 2;
1503 case 'n':
1504 case 'N':
1505 case 'e':
1506 case 'E':
1507 return format_reflog_person(sb,
1508 placeholder[1],
1509 c->pretty_ctx->reflog_info,
1510 &c->pretty_ctx->date_mode);
1512 return 0; /* unknown %g placeholder */
1513 case 'N':
1514 if (c->pretty_ctx->notes_message) {
1515 strbuf_addstr(sb, c->pretty_ctx->notes_message);
1516 return 1;
1518 return 0;
1521 if (placeholder[0] == 'G') {
1522 if (!c->signature_check.result)
1523 check_commit_signature(c->commit, &(c->signature_check));
1524 switch (placeholder[1]) {
1525 case 'G':
1526 if (c->signature_check.output)
1527 strbuf_addstr(sb, c->signature_check.output);
1528 break;
1529 case '?':
1530 switch (c->signature_check.result) {
1531 case 'G':
1532 switch (c->signature_check.trust_level) {
1533 case TRUST_UNDEFINED:
1534 case TRUST_NEVER:
1535 strbuf_addch(sb, 'U');
1536 break;
1537 default:
1538 strbuf_addch(sb, 'G');
1539 break;
1541 break;
1542 case 'B':
1543 case 'E':
1544 case 'N':
1545 case 'X':
1546 case 'Y':
1547 case 'R':
1548 strbuf_addch(sb, c->signature_check.result);
1550 break;
1551 case 'S':
1552 if (c->signature_check.signer)
1553 strbuf_addstr(sb, c->signature_check.signer);
1554 break;
1555 case 'K':
1556 if (c->signature_check.key)
1557 strbuf_addstr(sb, c->signature_check.key);
1558 break;
1559 case 'F':
1560 if (c->signature_check.fingerprint)
1561 strbuf_addstr(sb, c->signature_check.fingerprint);
1562 break;
1563 case 'P':
1564 if (c->signature_check.primary_key_fingerprint)
1565 strbuf_addstr(sb, c->signature_check.primary_key_fingerprint);
1566 break;
1567 case 'T':
1568 switch (c->signature_check.trust_level) {
1569 case TRUST_UNDEFINED:
1570 strbuf_addstr(sb, "undefined");
1571 break;
1572 case TRUST_NEVER:
1573 strbuf_addstr(sb, "never");
1574 break;
1575 case TRUST_MARGINAL:
1576 strbuf_addstr(sb, "marginal");
1577 break;
1578 case TRUST_FULLY:
1579 strbuf_addstr(sb, "fully");
1580 break;
1581 case TRUST_ULTIMATE:
1582 strbuf_addstr(sb, "ultimate");
1583 break;
1585 break;
1586 default:
1587 return 0;
1589 return 2;
1592 /* For the rest we have to parse the commit header. */
1593 if (!c->commit_header_parsed) {
1594 msg = c->message =
1595 repo_logmsg_reencode(c->repository, commit,
1596 &c->commit_encoding, "UTF-8");
1597 parse_commit_header(c);
1600 switch (placeholder[0]) {
1601 case 'a': /* author ... */
1602 return format_person_part(sb, placeholder[1],
1603 msg + c->author.off, c->author.len,
1604 &c->pretty_ctx->date_mode);
1605 case 'c': /* committer ... */
1606 return format_person_part(sb, placeholder[1],
1607 msg + c->committer.off, c->committer.len,
1608 &c->pretty_ctx->date_mode);
1609 case 'e': /* encoding */
1610 if (c->commit_encoding)
1611 strbuf_addstr(sb, c->commit_encoding);
1612 return 1;
1613 case 'B': /* raw body */
1614 /* message_off is always left at the initial newline */
1615 strbuf_addstr(sb, msg + c->message_off + 1);
1616 return 1;
1619 /* Now we need to parse the commit message. */
1620 if (!c->commit_message_parsed)
1621 parse_commit_message(c);
1623 switch (placeholder[0]) {
1624 case 's': /* subject */
1625 format_subject(sb, msg + c->subject_off, " ");
1626 return 1;
1627 case 'f': /* sanitized subject */
1628 eol = strchrnul(msg + c->subject_off, '\n');
1629 format_sanitized_subject(sb, msg + c->subject_off, eol - (msg + c->subject_off));
1630 return 1;
1631 case 'b': /* body */
1632 strbuf_addstr(sb, msg + c->body_off);
1633 return 1;
1636 if (skip_prefix(placeholder, "(trailers", &arg)) {
1637 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1638 struct string_list filter_list = STRING_LIST_INIT_NODUP;
1639 struct strbuf sepbuf = STRBUF_INIT;
1640 struct strbuf kvsepbuf = STRBUF_INIT;
1641 size_t ret = 0;
1643 opts.no_divider = 1;
1645 if (*arg == ':') {
1646 arg++;
1647 if (format_set_trailers_options(&opts, &filter_list, &sepbuf, &kvsepbuf, &arg, NULL))
1648 goto trailer_out;
1650 if (*arg == ')') {
1651 format_trailers_from_commit(sb, msg + c->subject_off, &opts);
1652 ret = arg - placeholder + 1;
1654 trailer_out:
1655 string_list_clear(&filter_list, 0);
1656 strbuf_release(&sepbuf);
1657 return ret;
1660 return 0; /* unknown placeholder */
1663 static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */
1664 const char *placeholder,
1665 struct format_commit_context *c)
1667 struct strbuf local_sb = STRBUF_INIT;
1668 size_t total_consumed = 0;
1669 int len, padding = c->padding;
1671 if (padding < 0) {
1672 const char *start = strrchr(sb->buf, '\n');
1673 int occupied;
1674 if (!start)
1675 start = sb->buf;
1676 occupied = utf8_strnwidth(start, strlen(start), 1);
1677 occupied += c->pretty_ctx->graph_width;
1678 padding = (-padding) - occupied;
1680 while (1) {
1681 int modifier = *placeholder == 'C';
1682 size_t consumed = format_commit_one(&local_sb, placeholder, c);
1683 total_consumed += consumed;
1685 if (!modifier)
1686 break;
1688 placeholder += consumed;
1689 if (*placeholder != '%')
1690 break;
1691 placeholder++;
1692 total_consumed++;
1694 len = utf8_strnwidth(local_sb.buf, local_sb.len, 1);
1696 if (c->flush_type == flush_left_and_steal) {
1697 const char *ch = sb->buf + sb->len - 1;
1698 while (len > padding && ch > sb->buf) {
1699 const char *p;
1700 if (*ch == ' ') {
1701 ch--;
1702 padding++;
1703 continue;
1705 /* check for trailing ansi sequences */
1706 if (*ch != 'm')
1707 break;
1708 p = ch - 1;
1709 while (p > sb->buf && ch - p < 10 && *p != '\033')
1710 p--;
1711 if (*p != '\033' ||
1712 ch + 1 - p != display_mode_esc_sequence_len(p))
1713 break;
1715 * got a good ansi sequence, put it back to
1716 * local_sb as we're cutting sb
1718 strbuf_insert(&local_sb, 0, p, ch + 1 - p);
1719 ch = p - 1;
1721 strbuf_setlen(sb, ch + 1 - sb->buf);
1722 c->flush_type = flush_left;
1725 if (len > padding) {
1726 switch (c->truncate) {
1727 case trunc_left:
1728 strbuf_utf8_replace(&local_sb,
1729 0, len - (padding - 2),
1730 "..");
1731 break;
1732 case trunc_middle:
1733 strbuf_utf8_replace(&local_sb,
1734 padding / 2 - 1,
1735 len - (padding - 2),
1736 "..");
1737 break;
1738 case trunc_right:
1739 strbuf_utf8_replace(&local_sb,
1740 padding - 2, len - (padding - 2),
1741 "..");
1742 break;
1743 case trunc_none:
1744 break;
1746 strbuf_addbuf(sb, &local_sb);
1747 } else {
1748 size_t sb_len = sb->len, offset = 0;
1749 if (c->flush_type == flush_left)
1750 offset = padding - len;
1751 else if (c->flush_type == flush_both)
1752 offset = (padding - len) / 2;
1754 * we calculate padding in columns, now
1755 * convert it back to chars
1757 padding = padding - len + local_sb.len;
1758 strbuf_addchars(sb, ' ', padding);
1759 memcpy(sb->buf + sb_len + offset, local_sb.buf,
1760 local_sb.len);
1762 strbuf_release(&local_sb);
1763 c->flush_type = no_flush;
1764 return total_consumed;
1767 static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */
1768 const char *placeholder,
1769 void *context)
1771 size_t consumed, orig_len;
1772 enum {
1773 NO_MAGIC,
1774 ADD_LF_BEFORE_NON_EMPTY,
1775 DEL_LF_BEFORE_EMPTY,
1776 ADD_SP_BEFORE_NON_EMPTY
1777 } magic = NO_MAGIC;
1779 switch (placeholder[0]) {
1780 case '-':
1781 magic = DEL_LF_BEFORE_EMPTY;
1782 break;
1783 case '+':
1784 magic = ADD_LF_BEFORE_NON_EMPTY;
1785 break;
1786 case ' ':
1787 magic = ADD_SP_BEFORE_NON_EMPTY;
1788 break;
1789 default:
1790 break;
1792 if (magic != NO_MAGIC) {
1793 placeholder++;
1795 switch (placeholder[0]) {
1796 case 'w':
1798 * `%+w()` cannot ever expand to a non-empty string,
1799 * and it potentially changes the layout of preceding
1800 * contents. We're thus not able to handle the magic in
1801 * this combination and refuse the pattern.
1803 return 0;
1807 orig_len = sb->len;
1808 if (((struct format_commit_context *)context)->flush_type != no_flush)
1809 consumed = format_and_pad_commit(sb, placeholder, context);
1810 else
1811 consumed = format_commit_one(sb, placeholder, context);
1812 if (magic == NO_MAGIC)
1813 return consumed;
1815 if ((orig_len == sb->len) && magic == DEL_LF_BEFORE_EMPTY) {
1816 while (sb->len && sb->buf[sb->len - 1] == '\n')
1817 strbuf_setlen(sb, sb->len - 1);
1818 } else if (orig_len != sb->len) {
1819 if (magic == ADD_LF_BEFORE_NON_EMPTY)
1820 strbuf_insertstr(sb, orig_len, "\n");
1821 else if (magic == ADD_SP_BEFORE_NON_EMPTY)
1822 strbuf_insertstr(sb, orig_len, " ");
1824 return consumed + 1;
1827 static size_t userformat_want_item(struct strbuf *sb, const char *placeholder,
1828 void *context)
1830 struct userformat_want *w = context;
1832 if (*placeholder == '+' || *placeholder == '-' || *placeholder == ' ')
1833 placeholder++;
1835 switch (*placeholder) {
1836 case 'N':
1837 w->notes = 1;
1838 break;
1839 case 'S':
1840 w->source = 1;
1841 break;
1842 case 'd':
1843 case 'D':
1844 w->decorate = 1;
1845 break;
1847 return 0;
1850 void userformat_find_requirements(const char *fmt, struct userformat_want *w)
1852 struct strbuf dummy = STRBUF_INIT;
1854 if (!fmt) {
1855 if (!user_format)
1856 return;
1857 fmt = user_format;
1859 strbuf_expand(&dummy, fmt, userformat_want_item, w);
1860 strbuf_release(&dummy);
1863 void repo_format_commit_message(struct repository *r,
1864 const struct commit *commit,
1865 const char *format, struct strbuf *sb,
1866 const struct pretty_print_context *pretty_ctx)
1868 struct format_commit_context context = {
1869 .repository = r,
1870 .commit = commit,
1871 .pretty_ctx = pretty_ctx,
1872 .wrap_start = sb->len
1874 const char *output_enc = pretty_ctx->output_encoding;
1875 const char *utf8 = "UTF-8";
1877 strbuf_expand(sb, format, format_commit_item, &context);
1878 rewrap_message_tail(sb, &context, 0, 0, 0);
1881 * Convert output to an actual output encoding; note that
1882 * format_commit_item() will always use UTF-8, so we don't
1883 * have to bother if that's what the output wants.
1885 if (output_enc) {
1886 if (same_encoding(utf8, output_enc))
1887 output_enc = NULL;
1888 } else {
1889 if (context.commit_encoding &&
1890 !same_encoding(context.commit_encoding, utf8))
1891 output_enc = context.commit_encoding;
1894 if (output_enc) {
1895 size_t outsz;
1896 char *out = reencode_string_len(sb->buf, sb->len,
1897 output_enc, utf8, &outsz);
1898 if (out)
1899 strbuf_attach(sb, out, outsz, outsz + 1);
1902 free(context.commit_encoding);
1903 repo_unuse_commit_buffer(r, commit, context.message);
1906 static void pp_header(struct pretty_print_context *pp,
1907 const char *encoding,
1908 const struct commit *commit,
1909 const char **msg_p,
1910 struct strbuf *sb)
1912 int parents_shown = 0;
1914 for (;;) {
1915 const char *name, *line = *msg_p;
1916 int linelen = get_one_line(*msg_p);
1918 if (!linelen)
1919 return;
1920 *msg_p += linelen;
1922 if (linelen == 1)
1923 /* End of header */
1924 return;
1926 if (pp->fmt == CMIT_FMT_RAW) {
1927 strbuf_add(sb, line, linelen);
1928 continue;
1931 if (starts_with(line, "parent ")) {
1932 if (linelen != the_hash_algo->hexsz + 8)
1933 die("bad parent line in commit");
1934 continue;
1937 if (!parents_shown) {
1938 unsigned num = commit_list_count(commit->parents);
1939 /* with enough slop */
1940 strbuf_grow(sb, num * (GIT_MAX_HEXSZ + 10) + 20);
1941 add_merge_info(pp, sb, commit);
1942 parents_shown = 1;
1946 * MEDIUM == DEFAULT shows only author with dates.
1947 * FULL shows both authors but not dates.
1948 * FULLER shows both authors and dates.
1950 if (skip_prefix(line, "author ", &name)) {
1951 strbuf_grow(sb, linelen + 80);
1952 pp_user_info(pp, "Author", sb, name, encoding);
1954 if (skip_prefix(line, "committer ", &name) &&
1955 (pp->fmt == CMIT_FMT_FULL || pp->fmt == CMIT_FMT_FULLER)) {
1956 strbuf_grow(sb, linelen + 80);
1957 pp_user_info(pp, "Commit", sb, name, encoding);
1962 void pp_title_line(struct pretty_print_context *pp,
1963 const char **msg_p,
1964 struct strbuf *sb,
1965 const char *encoding,
1966 int need_8bit_cte)
1968 static const int max_length = 78; /* per rfc2047 */
1969 struct strbuf title;
1971 strbuf_init(&title, 80);
1972 *msg_p = format_subject(&title, *msg_p,
1973 pp->preserve_subject ? "\n" : " ");
1975 strbuf_grow(sb, title.len + 1024);
1976 if (pp->print_email_subject) {
1977 if (pp->rev)
1978 fmt_output_email_subject(sb, pp->rev);
1979 if (pp->encode_email_headers &&
1980 needs_rfc2047_encoding(title.buf, title.len))
1981 add_rfc2047(sb, title.buf, title.len,
1982 encoding, RFC2047_SUBJECT);
1983 else
1984 strbuf_add_wrapped_bytes(sb, title.buf, title.len,
1985 -last_line_length(sb), 1, max_length);
1986 } else {
1987 strbuf_addbuf(sb, &title);
1989 strbuf_addch(sb, '\n');
1991 if (need_8bit_cte == 0) {
1992 int i;
1993 for (i = 0; i < pp->in_body_headers.nr; i++) {
1994 if (has_non_ascii(pp->in_body_headers.items[i].string)) {
1995 need_8bit_cte = 1;
1996 break;
2001 if (need_8bit_cte > 0) {
2002 const char *header_fmt =
2003 "MIME-Version: 1.0\n"
2004 "Content-Type: text/plain; charset=%s\n"
2005 "Content-Transfer-Encoding: 8bit\n";
2006 strbuf_addf(sb, header_fmt, encoding);
2008 if (pp->after_subject) {
2009 strbuf_addstr(sb, pp->after_subject);
2011 if (cmit_fmt_is_mail(pp->fmt)) {
2012 strbuf_addch(sb, '\n');
2015 if (pp->in_body_headers.nr) {
2016 int i;
2017 for (i = 0; i < pp->in_body_headers.nr; i++) {
2018 strbuf_addstr(sb, pp->in_body_headers.items[i].string);
2019 free(pp->in_body_headers.items[i].string);
2021 string_list_clear(&pp->in_body_headers, 0);
2022 strbuf_addch(sb, '\n');
2025 strbuf_release(&title);
2028 static int pp_utf8_width(const char *start, const char *end)
2030 int width = 0;
2031 size_t remain = end - start;
2033 while (remain) {
2034 int n = utf8_width(&start, &remain);
2035 if (n < 0 || !start)
2036 return -1;
2037 width += n;
2039 return width;
2042 static void strbuf_add_tabexpand(struct strbuf *sb, struct grep_opt *opt,
2043 int color, int tabwidth, const char *line,
2044 int linelen)
2046 const char *tab;
2048 while ((tab = memchr(line, '\t', linelen)) != NULL) {
2049 int width = pp_utf8_width(line, tab);
2052 * If it wasn't well-formed utf8, or it
2053 * had characters with badly defined
2054 * width (control characters etc), just
2055 * give up on trying to align things.
2057 if (width < 0)
2058 break;
2060 /* Output the data .. */
2061 append_line_with_color(sb, opt, line, tab - line, color,
2062 GREP_CONTEXT_BODY,
2063 GREP_HEADER_FIELD_MAX);
2065 /* .. and the de-tabified tab */
2066 strbuf_addchars(sb, ' ', tabwidth - (width % tabwidth));
2068 /* Skip over the printed part .. */
2069 linelen -= tab + 1 - line;
2070 line = tab + 1;
2074 * Print out everything after the last tab without
2075 * worrying about width - there's nothing more to
2076 * align.
2078 append_line_with_color(sb, opt, line, linelen, color, GREP_CONTEXT_BODY,
2079 GREP_HEADER_FIELD_MAX);
2083 * pp_handle_indent() prints out the intendation, and
2084 * the whole line (without the final newline), after
2085 * de-tabifying.
2087 static void pp_handle_indent(struct pretty_print_context *pp,
2088 struct strbuf *sb, int indent,
2089 const char *line, int linelen)
2091 struct grep_opt *opt = pp->rev ? &pp->rev->grep_filter : NULL;
2093 strbuf_addchars(sb, ' ', indent);
2094 if (pp->expand_tabs_in_log)
2095 strbuf_add_tabexpand(sb, opt, pp->color, pp->expand_tabs_in_log,
2096 line, linelen);
2097 else
2098 append_line_with_color(sb, opt, line, linelen, pp->color,
2099 GREP_CONTEXT_BODY,
2100 GREP_HEADER_FIELD_MAX);
2103 static int is_mboxrd_from(const char *line, int len)
2106 * a line matching /^From $/ here would only have len == 4
2107 * at this point because is_empty_line would've trimmed all
2108 * trailing space
2110 return len > 4 && starts_with(line + strspn(line, ">"), "From ");
2113 void pp_remainder(struct pretty_print_context *pp,
2114 const char **msg_p,
2115 struct strbuf *sb,
2116 int indent)
2118 struct grep_opt *opt = pp->rev ? &pp->rev->grep_filter : NULL;
2119 int first = 1;
2121 for (;;) {
2122 const char *line = *msg_p;
2123 int linelen = get_one_line(line);
2124 *msg_p += linelen;
2126 if (!linelen)
2127 break;
2129 if (is_blank_line(line, &linelen)) {
2130 if (first)
2131 continue;
2132 if (pp->fmt == CMIT_FMT_SHORT)
2133 break;
2135 first = 0;
2137 strbuf_grow(sb, linelen + indent + 20);
2138 if (indent)
2139 pp_handle_indent(pp, sb, indent, line, linelen);
2140 else if (pp->expand_tabs_in_log)
2141 strbuf_add_tabexpand(sb, opt, pp->color,
2142 pp->expand_tabs_in_log, line,
2143 linelen);
2144 else {
2145 if (pp->fmt == CMIT_FMT_MBOXRD &&
2146 is_mboxrd_from(line, linelen))
2147 strbuf_addch(sb, '>');
2149 append_line_with_color(sb, opt, line, linelen,
2150 pp->color, GREP_CONTEXT_BODY,
2151 GREP_HEADER_FIELD_MAX);
2153 strbuf_addch(sb, '\n');
2157 void pretty_print_commit(struct pretty_print_context *pp,
2158 const struct commit *commit,
2159 struct strbuf *sb)
2161 unsigned long beginning_of_body;
2162 int indent = 4;
2163 const char *msg;
2164 const char *reencoded;
2165 const char *encoding;
2166 int need_8bit_cte = pp->need_8bit_cte;
2168 if (pp->fmt == CMIT_FMT_USERFORMAT) {
2169 format_commit_message(commit, user_format, sb, pp);
2170 return;
2173 encoding = get_log_output_encoding();
2174 msg = reencoded = logmsg_reencode(commit, NULL, encoding);
2176 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
2177 indent = 0;
2180 * We need to check and emit Content-type: to mark it
2181 * as 8-bit if we haven't done so.
2183 if (cmit_fmt_is_mail(pp->fmt) && need_8bit_cte == 0) {
2184 int i, ch, in_body;
2186 for (in_body = i = 0; (ch = msg[i]); i++) {
2187 if (!in_body) {
2188 /* author could be non 7-bit ASCII but
2189 * the log may be so; skip over the
2190 * header part first.
2192 if (ch == '\n' && msg[i+1] == '\n')
2193 in_body = 1;
2195 else if (non_ascii(ch)) {
2196 need_8bit_cte = 1;
2197 break;
2202 pp_header(pp, encoding, commit, &msg, sb);
2203 if (pp->fmt != CMIT_FMT_ONELINE && !pp->print_email_subject) {
2204 strbuf_addch(sb, '\n');
2207 /* Skip excess blank lines at the beginning of body, if any... */
2208 msg = skip_blank_lines(msg);
2210 /* These formats treat the title line specially. */
2211 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
2212 pp_title_line(pp, &msg, sb, encoding, need_8bit_cte);
2214 beginning_of_body = sb->len;
2215 if (pp->fmt != CMIT_FMT_ONELINE)
2216 pp_remainder(pp, &msg, sb, indent);
2217 strbuf_rtrim(sb);
2219 /* Make sure there is an EOLN for the non-oneline case */
2220 if (pp->fmt != CMIT_FMT_ONELINE)
2221 strbuf_addch(sb, '\n');
2224 * The caller may append additional body text in e-mail
2225 * format. Make sure we did not strip the blank line
2226 * between the header and the body.
2228 if (cmit_fmt_is_mail(pp->fmt) && sb->len <= beginning_of_body)
2229 strbuf_addch(sb, '\n');
2231 unuse_commit_buffer(commit, reencoded);
2234 void pp_commit_easy(enum cmit_fmt fmt, const struct commit *commit,
2235 struct strbuf *sb)
2237 struct pretty_print_context pp = {0};
2238 pp.fmt = fmt;
2239 pretty_print_commit(&pp, commit, sb);