SubmittingPatches: use `--pretty=reference`
[git/debian.git] / pretty.c
blob5fc8b730d82d7b6a3155c77ba5660be23058f769
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"
16 static char *user_format;
17 static struct cmt_fmt_map {
18 const char *name;
19 enum cmit_fmt format;
20 int is_tformat;
21 int expand_tabs_in_log;
22 int is_alias;
23 enum date_mode_type default_date_mode_type;
24 const char *user_format;
25 } *commit_formats;
26 static size_t builtin_formats_len;
27 static size_t commit_formats_len;
28 static size_t commit_formats_alloc;
29 static struct cmt_fmt_map *find_commit_format(const char *sought);
31 int commit_format_is_empty(enum cmit_fmt fmt)
33 return fmt == CMIT_FMT_USERFORMAT && !*user_format;
36 static void save_user_format(struct rev_info *rev, const char *cp, int is_tformat)
38 free(user_format);
39 user_format = xstrdup(cp);
40 if (is_tformat)
41 rev->use_terminator = 1;
42 rev->commit_format = CMIT_FMT_USERFORMAT;
45 static int git_pretty_formats_config(const char *var, const char *value, void *cb)
47 struct cmt_fmt_map *commit_format = NULL;
48 const char *name;
49 const char *fmt;
50 int i;
52 if (!skip_prefix(var, "pretty.", &name))
53 return 0;
55 for (i = 0; i < builtin_formats_len; i++) {
56 if (!strcmp(commit_formats[i].name, name))
57 return 0;
60 for (i = builtin_formats_len; i < commit_formats_len; i++) {
61 if (!strcmp(commit_formats[i].name, name)) {
62 commit_format = &commit_formats[i];
63 break;
67 if (!commit_format) {
68 ALLOC_GROW(commit_formats, commit_formats_len+1,
69 commit_formats_alloc);
70 commit_format = &commit_formats[commit_formats_len];
71 memset(commit_format, 0, sizeof(*commit_format));
72 commit_formats_len++;
75 commit_format->name = xstrdup(name);
76 commit_format->format = CMIT_FMT_USERFORMAT;
77 if (git_config_string(&fmt, var, value))
78 return -1;
80 if (skip_prefix(fmt, "format:", &fmt))
81 commit_format->is_tformat = 0;
82 else if (skip_prefix(fmt, "tformat:", &fmt) || strchr(fmt, '%'))
83 commit_format->is_tformat = 1;
84 else
85 commit_format->is_alias = 1;
86 commit_format->user_format = fmt;
88 return 0;
91 static void setup_commit_formats(void)
93 struct cmt_fmt_map builtin_formats[] = {
94 { "raw", CMIT_FMT_RAW, 0, 0 },
95 { "medium", CMIT_FMT_MEDIUM, 0, 8 },
96 { "short", CMIT_FMT_SHORT, 0, 0 },
97 { "email", CMIT_FMT_EMAIL, 0, 0 },
98 { "mboxrd", CMIT_FMT_MBOXRD, 0, 0 },
99 { "fuller", CMIT_FMT_FULLER, 0, 8 },
100 { "full", CMIT_FMT_FULL, 0, 8 },
101 { "oneline", CMIT_FMT_ONELINE, 1, 0 },
102 { "reference", CMIT_FMT_USERFORMAT, 1, 0,
103 0, DATE_SHORT, "%C(auto)%h (%s, %ad)" },
105 * Please update $__git_log_pretty_formats in
106 * git-completion.bash when you add new formats.
109 commit_formats_len = ARRAY_SIZE(builtin_formats);
110 builtin_formats_len = commit_formats_len;
111 ALLOC_GROW(commit_formats, commit_formats_len, commit_formats_alloc);
112 COPY_ARRAY(commit_formats, builtin_formats,
113 ARRAY_SIZE(builtin_formats));
115 git_config(git_pretty_formats_config, NULL);
118 static struct cmt_fmt_map *find_commit_format_recursive(const char *sought,
119 const char *original,
120 int num_redirections)
122 struct cmt_fmt_map *found = NULL;
123 size_t found_match_len = 0;
124 int i;
126 if (num_redirections >= commit_formats_len)
127 die("invalid --pretty format: "
128 "'%s' references an alias which points to itself",
129 original);
131 for (i = 0; i < commit_formats_len; i++) {
132 size_t match_len;
134 if (!starts_with(commit_formats[i].name, sought))
135 continue;
137 match_len = strlen(commit_formats[i].name);
138 if (found == NULL || found_match_len > match_len) {
139 found = &commit_formats[i];
140 found_match_len = match_len;
144 if (found && found->is_alias) {
145 found = find_commit_format_recursive(found->user_format,
146 original,
147 num_redirections+1);
150 return found;
153 static struct cmt_fmt_map *find_commit_format(const char *sought)
155 if (!commit_formats)
156 setup_commit_formats();
158 return find_commit_format_recursive(sought, sought, 0);
161 void get_commit_format(const char *arg, struct rev_info *rev)
163 struct cmt_fmt_map *commit_format;
165 rev->use_terminator = 0;
166 if (!arg) {
167 rev->commit_format = CMIT_FMT_DEFAULT;
168 return;
170 if (skip_prefix(arg, "format:", &arg)) {
171 save_user_format(rev, arg, 0);
172 return;
175 if (!*arg || skip_prefix(arg, "tformat:", &arg) || strchr(arg, '%')) {
176 save_user_format(rev, arg, 1);
177 return;
180 commit_format = find_commit_format(arg);
181 if (!commit_format)
182 die("invalid --pretty format: %s", arg);
184 rev->commit_format = commit_format->format;
185 rev->use_terminator = commit_format->is_tformat;
186 rev->expand_tabs_in_log_default = commit_format->expand_tabs_in_log;
187 if (!rev->date_mode_explicit && commit_format->default_date_mode_type)
188 rev->date_mode.type = commit_format->default_date_mode_type;
189 if (commit_format->format == CMIT_FMT_USERFORMAT) {
190 save_user_format(rev, commit_format->user_format,
191 commit_format->is_tformat);
196 * Generic support for pretty-printing the header
198 static int get_one_line(const char *msg)
200 int ret = 0;
202 for (;;) {
203 char c = *msg++;
204 if (!c)
205 break;
206 ret++;
207 if (c == '\n')
208 break;
210 return ret;
213 /* High bit set, or ISO-2022-INT */
214 static int non_ascii(int ch)
216 return !isascii(ch) || ch == '\033';
219 int has_non_ascii(const char *s)
221 int ch;
222 if (!s)
223 return 0;
224 while ((ch = *s++) != '\0') {
225 if (non_ascii(ch))
226 return 1;
228 return 0;
231 static int is_rfc822_special(char ch)
233 switch (ch) {
234 case '(':
235 case ')':
236 case '<':
237 case '>':
238 case '[':
239 case ']':
240 case ':':
241 case ';':
242 case '@':
243 case ',':
244 case '.':
245 case '"':
246 case '\\':
247 return 1;
248 default:
249 return 0;
253 static int needs_rfc822_quoting(const char *s, int len)
255 int i;
256 for (i = 0; i < len; i++)
257 if (is_rfc822_special(s[i]))
258 return 1;
259 return 0;
262 static int last_line_length(struct strbuf *sb)
264 int i;
266 /* How many bytes are already used on the last line? */
267 for (i = sb->len - 1; i >= 0; i--)
268 if (sb->buf[i] == '\n')
269 break;
270 return sb->len - (i + 1);
273 static void add_rfc822_quoted(struct strbuf *out, const char *s, int len)
275 int i;
277 /* just a guess, we may have to also backslash-quote */
278 strbuf_grow(out, len + 2);
280 strbuf_addch(out, '"');
281 for (i = 0; i < len; i++) {
282 switch (s[i]) {
283 case '"':
284 case '\\':
285 strbuf_addch(out, '\\');
286 /* fall through */
287 default:
288 strbuf_addch(out, s[i]);
291 strbuf_addch(out, '"');
294 enum rfc2047_type {
295 RFC2047_SUBJECT,
296 RFC2047_ADDRESS
299 static int is_rfc2047_special(char ch, enum rfc2047_type type)
302 * rfc2047, section 4.2:
304 * 8-bit values which correspond to printable ASCII characters other
305 * than "=", "?", and "_" (underscore), MAY be represented as those
306 * characters. (But see section 5 for restrictions.) In
307 * particular, SPACE and TAB MUST NOT be represented as themselves
308 * within encoded words.
312 * rule out non-ASCII characters and non-printable characters (the
313 * non-ASCII check should be redundant as isprint() is not localized
314 * and only knows about ASCII, but be defensive about that)
316 if (non_ascii(ch) || !isprint(ch))
317 return 1;
320 * rule out special printable characters (' ' should be the only
321 * whitespace character considered printable, but be defensive and use
322 * isspace())
324 if (isspace(ch) || ch == '=' || ch == '?' || ch == '_')
325 return 1;
328 * rfc2047, section 5.3:
330 * As a replacement for a 'word' entity within a 'phrase', for example,
331 * one that precedes an address in a From, To, or Cc header. The ABNF
332 * definition for 'phrase' from RFC 822 thus becomes:
334 * phrase = 1*( encoded-word / word )
336 * In this case the set of characters that may be used in a "Q"-encoded
337 * 'encoded-word' is restricted to: <upper and lower case ASCII
338 * letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
339 * (underscore, ASCII 95.)>. An 'encoded-word' that appears within a
340 * 'phrase' MUST be separated from any adjacent 'word', 'text' or
341 * 'special' by 'linear-white-space'.
344 if (type != RFC2047_ADDRESS)
345 return 0;
347 /* '=' and '_' are special cases and have been checked above */
348 return !(isalnum(ch) || ch == '!' || ch == '*' || ch == '+' || ch == '-' || ch == '/');
351 static int needs_rfc2047_encoding(const char *line, int len)
353 int i;
355 for (i = 0; i < len; i++) {
356 int ch = line[i];
357 if (non_ascii(ch) || ch == '\n')
358 return 1;
359 if ((i + 1 < len) && (ch == '=' && line[i+1] == '?'))
360 return 1;
363 return 0;
366 static void add_rfc2047(struct strbuf *sb, const char *line, size_t len,
367 const char *encoding, enum rfc2047_type type)
369 static const int max_encoded_length = 76; /* per rfc2047 */
370 int i;
371 int line_len = last_line_length(sb);
373 strbuf_grow(sb, len * 3 + strlen(encoding) + 100);
374 strbuf_addf(sb, "=?%s?q?", encoding);
375 line_len += strlen(encoding) + 5; /* 5 for =??q? */
377 while (len) {
379 * RFC 2047, section 5 (3):
381 * Each 'encoded-word' MUST represent an integral number of
382 * characters. A multi-octet character may not be split across
383 * adjacent 'encoded- word's.
385 const unsigned char *p = (const unsigned char *)line;
386 int chrlen = mbs_chrlen(&line, &len, encoding);
387 int is_special = (chrlen > 1) || is_rfc2047_special(*p, type);
389 /* "=%02X" * chrlen, or the byte itself */
390 const char *encoded_fmt = is_special ? "=%02X" : "%c";
391 int encoded_len = is_special ? 3 * chrlen : 1;
394 * According to RFC 2047, we could encode the special character
395 * ' ' (space) with '_' (underscore) for readability. But many
396 * programs do not understand this and just leave the
397 * underscore in place. Thus, we do nothing special here, which
398 * causes ' ' to be encoded as '=20', avoiding this problem.
401 if (line_len + encoded_len + 2 > max_encoded_length) {
402 /* It won't fit with trailing "?=" --- break the line */
403 strbuf_addf(sb, "?=\n =?%s?q?", encoding);
404 line_len = strlen(encoding) + 5 + 1; /* =??q? plus SP */
407 for (i = 0; i < chrlen; i++)
408 strbuf_addf(sb, encoded_fmt, p[i]);
409 line_len += encoded_len;
411 strbuf_addstr(sb, "?=");
414 const char *show_ident_date(const struct ident_split *ident,
415 const struct date_mode *mode)
417 timestamp_t date = 0;
418 long tz = 0;
420 if (ident->date_begin && ident->date_end)
421 date = parse_timestamp(ident->date_begin, NULL, 10);
422 if (date_overflows(date))
423 date = 0;
424 else {
425 if (ident->tz_begin && ident->tz_end)
426 tz = strtol(ident->tz_begin, NULL, 10);
427 if (tz >= INT_MAX || tz <= INT_MIN)
428 tz = 0;
430 return show_date(date, tz, mode);
433 void pp_user_info(struct pretty_print_context *pp,
434 const char *what, struct strbuf *sb,
435 const char *line, const char *encoding)
437 struct ident_split ident;
438 char *line_end;
439 const char *mailbuf, *namebuf;
440 size_t namelen, maillen;
441 int max_length = 78; /* per rfc2822 */
443 if (pp->fmt == CMIT_FMT_ONELINE)
444 return;
446 line_end = strchrnul(line, '\n');
447 if (split_ident_line(&ident, line, line_end - line))
448 return;
450 mailbuf = ident.mail_begin;
451 maillen = ident.mail_end - ident.mail_begin;
452 namebuf = ident.name_begin;
453 namelen = ident.name_end - ident.name_begin;
455 if (pp->mailmap)
456 map_user(pp->mailmap, &mailbuf, &maillen, &namebuf, &namelen);
458 if (cmit_fmt_is_mail(pp->fmt)) {
459 if (pp->from_ident && ident_cmp(pp->from_ident, &ident)) {
460 struct strbuf buf = STRBUF_INIT;
462 strbuf_addstr(&buf, "From: ");
463 strbuf_add(&buf, namebuf, namelen);
464 strbuf_addstr(&buf, " <");
465 strbuf_add(&buf, mailbuf, maillen);
466 strbuf_addstr(&buf, ">\n");
467 string_list_append(&pp->in_body_headers,
468 strbuf_detach(&buf, NULL));
470 mailbuf = pp->from_ident->mail_begin;
471 maillen = pp->from_ident->mail_end - mailbuf;
472 namebuf = pp->from_ident->name_begin;
473 namelen = pp->from_ident->name_end - namebuf;
476 strbuf_addstr(sb, "From: ");
477 if (needs_rfc2047_encoding(namebuf, namelen)) {
478 add_rfc2047(sb, namebuf, namelen,
479 encoding, RFC2047_ADDRESS);
480 max_length = 76; /* per rfc2047 */
481 } else if (needs_rfc822_quoting(namebuf, namelen)) {
482 struct strbuf quoted = STRBUF_INIT;
483 add_rfc822_quoted(&quoted, namebuf, namelen);
484 strbuf_add_wrapped_bytes(sb, quoted.buf, quoted.len,
485 -6, 1, max_length);
486 strbuf_release(&quoted);
487 } else {
488 strbuf_add_wrapped_bytes(sb, namebuf, namelen,
489 -6, 1, max_length);
492 if (max_length <
493 last_line_length(sb) + strlen(" <") + maillen + strlen(">"))
494 strbuf_addch(sb, '\n');
495 strbuf_addf(sb, " <%.*s>\n", (int)maillen, mailbuf);
496 } else {
497 strbuf_addf(sb, "%s: %.*s%.*s <%.*s>\n", what,
498 (pp->fmt == CMIT_FMT_FULLER) ? 4 : 0, " ",
499 (int)namelen, namebuf, (int)maillen, mailbuf);
502 switch (pp->fmt) {
503 case CMIT_FMT_MEDIUM:
504 strbuf_addf(sb, "Date: %s\n",
505 show_ident_date(&ident, &pp->date_mode));
506 break;
507 case CMIT_FMT_EMAIL:
508 case CMIT_FMT_MBOXRD:
509 strbuf_addf(sb, "Date: %s\n",
510 show_ident_date(&ident, DATE_MODE(RFC2822)));
511 break;
512 case CMIT_FMT_FULLER:
513 strbuf_addf(sb, "%sDate: %s\n", what,
514 show_ident_date(&ident, &pp->date_mode));
515 break;
516 default:
517 /* notin' */
518 break;
522 static int is_blank_line(const char *line, int *len_p)
524 int len = *len_p;
525 while (len && isspace(line[len - 1]))
526 len--;
527 *len_p = len;
528 return !len;
531 const char *skip_blank_lines(const char *msg)
533 for (;;) {
534 int linelen = get_one_line(msg);
535 int ll = linelen;
536 if (!linelen)
537 break;
538 if (!is_blank_line(msg, &ll))
539 break;
540 msg += linelen;
542 return msg;
545 static void add_merge_info(const struct pretty_print_context *pp,
546 struct strbuf *sb, const struct commit *commit)
548 struct commit_list *parent = commit->parents;
550 if ((pp->fmt == CMIT_FMT_ONELINE) || (cmit_fmt_is_mail(pp->fmt)) ||
551 !parent || !parent->next)
552 return;
554 strbuf_addstr(sb, "Merge:");
556 while (parent) {
557 struct object_id *oidp = &parent->item->object.oid;
558 strbuf_addch(sb, ' ');
559 if (pp->abbrev)
560 strbuf_add_unique_abbrev(sb, oidp, pp->abbrev);
561 else
562 strbuf_addstr(sb, oid_to_hex(oidp));
563 parent = parent->next;
565 strbuf_addch(sb, '\n');
568 static char *get_header(const char *msg, const char *key)
570 size_t len;
571 const char *v = find_commit_header(msg, key, &len);
572 return v ? xmemdupz(v, len) : NULL;
575 static char *replace_encoding_header(char *buf, const char *encoding)
577 struct strbuf tmp = STRBUF_INIT;
578 size_t start, len;
579 char *cp = buf;
581 /* guess if there is an encoding header before a \n\n */
582 while (!starts_with(cp, "encoding ")) {
583 cp = strchr(cp, '\n');
584 if (!cp || *++cp == '\n')
585 return buf;
587 start = cp - buf;
588 cp = strchr(cp, '\n');
589 if (!cp)
590 return buf; /* should not happen but be defensive */
591 len = cp + 1 - (buf + start);
593 strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
594 if (is_encoding_utf8(encoding)) {
595 /* we have re-coded to UTF-8; drop the header */
596 strbuf_remove(&tmp, start, len);
597 } else {
598 /* just replaces XXXX in 'encoding XXXX\n' */
599 strbuf_splice(&tmp, start + strlen("encoding "),
600 len - strlen("encoding \n"),
601 encoding, strlen(encoding));
603 return strbuf_detach(&tmp, NULL);
606 const char *repo_logmsg_reencode(struct repository *r,
607 const struct commit *commit,
608 char **commit_encoding,
609 const char *output_encoding)
611 static const char *utf8 = "UTF-8";
612 const char *use_encoding;
613 char *encoding;
614 const char *msg = repo_get_commit_buffer(r, commit, NULL);
615 char *out;
617 if (!output_encoding || !*output_encoding) {
618 if (commit_encoding)
619 *commit_encoding = get_header(msg, "encoding");
620 return msg;
622 encoding = get_header(msg, "encoding");
623 if (commit_encoding)
624 *commit_encoding = encoding;
625 use_encoding = encoding ? encoding : utf8;
626 if (same_encoding(use_encoding, output_encoding)) {
628 * No encoding work to be done. If we have no encoding header
629 * at all, then there's nothing to do, and we can return the
630 * message verbatim (whether newly allocated or not).
632 if (!encoding)
633 return msg;
636 * Otherwise, we still want to munge the encoding header in the
637 * result, which will be done by modifying the buffer. If we
638 * are using a fresh copy, we can reuse it. But if we are using
639 * the cached copy from get_commit_buffer, we need to duplicate it
640 * to avoid munging the cached copy.
642 if (msg == get_cached_commit_buffer(r, commit, NULL))
643 out = xstrdup(msg);
644 else
645 out = (char *)msg;
647 else {
649 * There's actual encoding work to do. Do the reencoding, which
650 * still leaves the header to be replaced in the next step. At
651 * this point, we are done with msg. If we allocated a fresh
652 * copy, we can free it.
654 out = reencode_string(msg, output_encoding, use_encoding);
655 if (out)
656 repo_unuse_commit_buffer(r, commit, msg);
660 * This replacement actually consumes the buffer we hand it, so we do
661 * not have to worry about freeing the old "out" here.
663 if (out)
664 out = replace_encoding_header(out, output_encoding);
666 if (!commit_encoding)
667 free(encoding);
669 * If the re-encoding failed, out might be NULL here; in that
670 * case we just return the commit message verbatim.
672 return out ? out : msg;
675 static int mailmap_name(const char **email, size_t *email_len,
676 const char **name, size_t *name_len)
678 static struct string_list *mail_map;
679 if (!mail_map) {
680 mail_map = xcalloc(1, sizeof(*mail_map));
681 read_mailmap(mail_map, NULL);
683 return mail_map->nr && map_user(mail_map, email, email_len, name, name_len);
686 static size_t format_person_part(struct strbuf *sb, char part,
687 const char *msg, int len,
688 const struct date_mode *dmode)
690 /* currently all placeholders have same length */
691 const int placeholder_len = 2;
692 struct ident_split s;
693 const char *name, *mail;
694 size_t maillen, namelen;
696 if (split_ident_line(&s, msg, len) < 0)
697 goto skip;
699 name = s.name_begin;
700 namelen = s.name_end - s.name_begin;
701 mail = s.mail_begin;
702 maillen = s.mail_end - s.mail_begin;
704 if (part == 'N' || part == 'E') /* mailmap lookup */
705 mailmap_name(&mail, &maillen, &name, &namelen);
706 if (part == 'n' || part == 'N') { /* name */
707 strbuf_add(sb, name, namelen);
708 return placeholder_len;
710 if (part == 'e' || part == 'E') { /* email */
711 strbuf_add(sb, mail, maillen);
712 return placeholder_len;
715 if (!s.date_begin)
716 goto skip;
718 if (part == 't') { /* date, UNIX timestamp */
719 strbuf_add(sb, s.date_begin, s.date_end - s.date_begin);
720 return placeholder_len;
723 switch (part) {
724 case 'd': /* date */
725 strbuf_addstr(sb, show_ident_date(&s, dmode));
726 return placeholder_len;
727 case 'D': /* date, RFC2822 style */
728 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RFC2822)));
729 return placeholder_len;
730 case 'r': /* date, relative */
731 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RELATIVE)));
732 return placeholder_len;
733 case 'i': /* date, ISO 8601-like */
734 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601)));
735 return placeholder_len;
736 case 'I': /* date, ISO 8601 strict */
737 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601_STRICT)));
738 return placeholder_len;
739 case 's':
740 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(SHORT)));
741 return placeholder_len;
744 skip:
746 * reading from either a bogus commit, or a reflog entry with
747 * %gn, %ge, etc.; 'sb' cannot be updated, but we still need
748 * to compute a valid return value.
750 if (part == 'n' || part == 'e' || part == 't' || part == 'd'
751 || part == 'D' || part == 'r' || part == 'i')
752 return placeholder_len;
754 return 0; /* unknown placeholder */
757 struct chunk {
758 size_t off;
759 size_t len;
762 enum flush_type {
763 no_flush,
764 flush_right,
765 flush_left,
766 flush_left_and_steal,
767 flush_both
770 enum trunc_type {
771 trunc_none,
772 trunc_left,
773 trunc_middle,
774 trunc_right
777 struct format_commit_context {
778 const struct commit *commit;
779 const struct pretty_print_context *pretty_ctx;
780 unsigned commit_header_parsed:1;
781 unsigned commit_message_parsed:1;
782 struct signature_check signature_check;
783 enum flush_type flush_type;
784 enum trunc_type truncate;
785 const char *message;
786 char *commit_encoding;
787 size_t width, indent1, indent2;
788 int auto_color;
789 int padding;
791 /* These offsets are relative to the start of the commit message. */
792 struct chunk author;
793 struct chunk committer;
794 size_t message_off;
795 size_t subject_off;
796 size_t body_off;
798 /* The following ones are relative to the result struct strbuf. */
799 size_t wrap_start;
802 static void parse_commit_header(struct format_commit_context *context)
804 const char *msg = context->message;
805 int i;
807 for (i = 0; msg[i]; i++) {
808 const char *name;
809 int eol;
810 for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
811 ; /* do nothing */
813 if (i == eol) {
814 break;
815 } else if (skip_prefix(msg + i, "author ", &name)) {
816 context->author.off = name - msg;
817 context->author.len = msg + eol - name;
818 } else if (skip_prefix(msg + i, "committer ", &name)) {
819 context->committer.off = name - msg;
820 context->committer.len = msg + eol - name;
822 i = eol;
824 context->message_off = i;
825 context->commit_header_parsed = 1;
828 static int istitlechar(char c)
830 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
831 (c >= '0' && c <= '9') || c == '.' || c == '_';
834 static void format_sanitized_subject(struct strbuf *sb, const char *msg)
836 size_t trimlen;
837 size_t start_len = sb->len;
838 int space = 2;
840 for (; *msg && *msg != '\n'; msg++) {
841 if (istitlechar(*msg)) {
842 if (space == 1)
843 strbuf_addch(sb, '-');
844 space = 0;
845 strbuf_addch(sb, *msg);
846 if (*msg == '.')
847 while (*(msg+1) == '.')
848 msg++;
849 } else
850 space |= 1;
853 /* trim any trailing '.' or '-' characters */
854 trimlen = 0;
855 while (sb->len - trimlen > start_len &&
856 (sb->buf[sb->len - 1 - trimlen] == '.'
857 || sb->buf[sb->len - 1 - trimlen] == '-'))
858 trimlen++;
859 strbuf_remove(sb, sb->len - trimlen, trimlen);
862 const char *format_subject(struct strbuf *sb, const char *msg,
863 const char *line_separator)
865 int first = 1;
867 for (;;) {
868 const char *line = msg;
869 int linelen = get_one_line(line);
871 msg += linelen;
872 if (!linelen || is_blank_line(line, &linelen))
873 break;
875 if (!sb)
876 continue;
877 strbuf_grow(sb, linelen + 2);
878 if (!first)
879 strbuf_addstr(sb, line_separator);
880 strbuf_add(sb, line, linelen);
881 first = 0;
883 return msg;
886 static void parse_commit_message(struct format_commit_context *c)
888 const char *msg = c->message + c->message_off;
889 const char *start = c->message;
891 msg = skip_blank_lines(msg);
892 c->subject_off = msg - start;
894 msg = format_subject(NULL, msg, NULL);
895 msg = skip_blank_lines(msg);
896 c->body_off = msg - start;
898 c->commit_message_parsed = 1;
901 static void strbuf_wrap(struct strbuf *sb, size_t pos,
902 size_t width, size_t indent1, size_t indent2)
904 struct strbuf tmp = STRBUF_INIT;
906 if (pos)
907 strbuf_add(&tmp, sb->buf, pos);
908 strbuf_add_wrapped_text(&tmp, sb->buf + pos,
909 (int) indent1, (int) indent2, (int) width);
910 strbuf_swap(&tmp, sb);
911 strbuf_release(&tmp);
914 static void rewrap_message_tail(struct strbuf *sb,
915 struct format_commit_context *c,
916 size_t new_width, size_t new_indent1,
917 size_t new_indent2)
919 if (c->width == new_width && c->indent1 == new_indent1 &&
920 c->indent2 == new_indent2)
921 return;
922 if (c->wrap_start < sb->len)
923 strbuf_wrap(sb, c->wrap_start, c->width, c->indent1, c->indent2);
924 c->wrap_start = sb->len;
925 c->width = new_width;
926 c->indent1 = new_indent1;
927 c->indent2 = new_indent2;
930 static int format_reflog_person(struct strbuf *sb,
931 char part,
932 struct reflog_walk_info *log,
933 const struct date_mode *dmode)
935 const char *ident;
937 if (!log)
938 return 2;
940 ident = get_reflog_ident(log);
941 if (!ident)
942 return 2;
944 return format_person_part(sb, part, ident, strlen(ident), dmode);
947 static size_t parse_color(struct strbuf *sb, /* in UTF-8 */
948 const char *placeholder,
949 struct format_commit_context *c)
951 const char *rest = placeholder;
952 const char *basic_color = NULL;
954 if (placeholder[1] == '(') {
955 const char *begin = placeholder + 2;
956 const char *end = strchr(begin, ')');
957 char color[COLOR_MAXLEN];
959 if (!end)
960 return 0;
962 if (skip_prefix(begin, "auto,", &begin)) {
963 if (!want_color(c->pretty_ctx->color))
964 return end - placeholder + 1;
965 } else if (skip_prefix(begin, "always,", &begin)) {
966 /* nothing to do; we do not respect want_color at all */
967 } else {
968 /* the default is the same as "auto" */
969 if (!want_color(c->pretty_ctx->color))
970 return end - placeholder + 1;
973 if (color_parse_mem(begin, end - begin, color) < 0)
974 die(_("unable to parse --pretty format"));
975 strbuf_addstr(sb, color);
976 return end - placeholder + 1;
980 * We handle things like "%C(red)" above; for historical reasons, there
981 * are a few colors that can be specified without parentheses (and
982 * they cannot support things like "auto" or "always" at all).
984 if (skip_prefix(placeholder + 1, "red", &rest))
985 basic_color = GIT_COLOR_RED;
986 else if (skip_prefix(placeholder + 1, "green", &rest))
987 basic_color = GIT_COLOR_GREEN;
988 else if (skip_prefix(placeholder + 1, "blue", &rest))
989 basic_color = GIT_COLOR_BLUE;
990 else if (skip_prefix(placeholder + 1, "reset", &rest))
991 basic_color = GIT_COLOR_RESET;
993 if (basic_color && want_color(c->pretty_ctx->color))
994 strbuf_addstr(sb, basic_color);
996 return rest - placeholder;
999 static size_t parse_padding_placeholder(const char *placeholder,
1000 struct format_commit_context *c)
1002 const char *ch = placeholder;
1003 enum flush_type flush_type;
1004 int to_column = 0;
1006 switch (*ch++) {
1007 case '<':
1008 flush_type = flush_right;
1009 break;
1010 case '>':
1011 if (*ch == '<') {
1012 flush_type = flush_both;
1013 ch++;
1014 } else if (*ch == '>') {
1015 flush_type = flush_left_and_steal;
1016 ch++;
1017 } else
1018 flush_type = flush_left;
1019 break;
1020 default:
1021 return 0;
1024 /* the next value means "wide enough to that column" */
1025 if (*ch == '|') {
1026 to_column = 1;
1027 ch++;
1030 if (*ch == '(') {
1031 const char *start = ch + 1;
1032 const char *end = start + strcspn(start, ",)");
1033 char *next;
1034 int width;
1035 if (!end || end == start)
1036 return 0;
1037 width = strtol(start, &next, 10);
1038 if (next == start || width == 0)
1039 return 0;
1040 if (width < 0) {
1041 if (to_column)
1042 width += term_columns();
1043 if (width < 0)
1044 return 0;
1046 c->padding = to_column ? -width : width;
1047 c->flush_type = flush_type;
1049 if (*end == ',') {
1050 start = end + 1;
1051 end = strchr(start, ')');
1052 if (!end || end == start)
1053 return 0;
1054 if (starts_with(start, "trunc)"))
1055 c->truncate = trunc_right;
1056 else if (starts_with(start, "ltrunc)"))
1057 c->truncate = trunc_left;
1058 else if (starts_with(start, "mtrunc)"))
1059 c->truncate = trunc_middle;
1060 else
1061 return 0;
1062 } else
1063 c->truncate = trunc_none;
1065 return end - placeholder + 1;
1067 return 0;
1070 static int match_placeholder_arg_value(const char *to_parse, const char *candidate,
1071 const char **end, const char **valuestart,
1072 size_t *valuelen)
1074 const char *p;
1076 if (!(skip_prefix(to_parse, candidate, &p)))
1077 return 0;
1078 if (valuestart) {
1079 if (*p == '=') {
1080 *valuestart = p + 1;
1081 *valuelen = strcspn(*valuestart, ",)");
1082 p = *valuestart + *valuelen;
1083 } else {
1084 if (*p != ',' && *p != ')')
1085 return 0;
1086 *valuestart = NULL;
1087 *valuelen = 0;
1090 if (*p == ',') {
1091 *end = p + 1;
1092 return 1;
1094 if (*p == ')') {
1095 *end = p;
1096 return 1;
1098 return 0;
1101 static int match_placeholder_bool_arg(const char *to_parse, const char *candidate,
1102 const char **end, int *val)
1104 const char *argval;
1105 char *strval;
1106 size_t arglen;
1107 int v;
1109 if (!match_placeholder_arg_value(to_parse, candidate, end, &argval, &arglen))
1110 return 0;
1112 if (!argval) {
1113 *val = 1;
1114 return 1;
1117 strval = xstrndup(argval, arglen);
1118 v = git_parse_maybe_bool(strval);
1119 free(strval);
1121 if (v == -1)
1122 return 0;
1124 *val = v;
1126 return 1;
1129 static int format_trailer_match_cb(const struct strbuf *key, void *ud)
1131 const struct string_list *list = ud;
1132 const struct string_list_item *item;
1134 for_each_string_list_item (item, list) {
1135 if (key->len == (uintptr_t)item->util &&
1136 !strncasecmp(item->string, key->buf, key->len))
1137 return 1;
1139 return 0;
1142 static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
1143 const char *placeholder,
1144 void *context)
1146 struct format_commit_context *c = context;
1147 const struct commit *commit = c->commit;
1148 const char *msg = c->message;
1149 struct commit_list *p;
1150 const char *arg;
1151 size_t res;
1152 char **slot;
1154 /* these are independent of the commit */
1155 res = strbuf_expand_literal_cb(sb, placeholder, NULL);
1156 if (res)
1157 return res;
1159 switch (placeholder[0]) {
1160 case 'C':
1161 if (starts_with(placeholder + 1, "(auto)")) {
1162 c->auto_color = want_color(c->pretty_ctx->color);
1163 if (c->auto_color && sb->len)
1164 strbuf_addstr(sb, GIT_COLOR_RESET);
1165 return 7; /* consumed 7 bytes, "C(auto)" */
1166 } else {
1167 int ret = parse_color(sb, placeholder, c);
1168 if (ret)
1169 c->auto_color = 0;
1171 * Otherwise, we decided to treat %C<unknown>
1172 * as a literal string, and the previous
1173 * %C(auto) is still valid.
1175 return ret;
1177 case 'w':
1178 if (placeholder[1] == '(') {
1179 unsigned long width = 0, indent1 = 0, indent2 = 0;
1180 char *next;
1181 const char *start = placeholder + 2;
1182 const char *end = strchr(start, ')');
1183 if (!end)
1184 return 0;
1185 if (end > start) {
1186 width = strtoul(start, &next, 10);
1187 if (*next == ',') {
1188 indent1 = strtoul(next + 1, &next, 10);
1189 if (*next == ',') {
1190 indent2 = strtoul(next + 1,
1191 &next, 10);
1194 if (*next != ')')
1195 return 0;
1197 rewrap_message_tail(sb, c, width, indent1, indent2);
1198 return end - placeholder + 1;
1199 } else
1200 return 0;
1202 case '<':
1203 case '>':
1204 return parse_padding_placeholder(placeholder, c);
1207 /* these depend on the commit */
1208 if (!commit->object.parsed)
1209 parse_object(the_repository, &commit->object.oid);
1211 switch (placeholder[0]) {
1212 case 'H': /* commit hash */
1213 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1214 strbuf_addstr(sb, oid_to_hex(&commit->object.oid));
1215 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1216 return 1;
1217 case 'h': /* abbreviated commit hash */
1218 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1219 strbuf_add_unique_abbrev(sb, &commit->object.oid,
1220 c->pretty_ctx->abbrev);
1221 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1222 return 1;
1223 case 'T': /* tree hash */
1224 strbuf_addstr(sb, oid_to_hex(get_commit_tree_oid(commit)));
1225 return 1;
1226 case 't': /* abbreviated tree hash */
1227 strbuf_add_unique_abbrev(sb,
1228 get_commit_tree_oid(commit),
1229 c->pretty_ctx->abbrev);
1230 return 1;
1231 case 'P': /* parent hashes */
1232 for (p = commit->parents; p; p = p->next) {
1233 if (p != commit->parents)
1234 strbuf_addch(sb, ' ');
1235 strbuf_addstr(sb, oid_to_hex(&p->item->object.oid));
1237 return 1;
1238 case 'p': /* abbreviated parent hashes */
1239 for (p = commit->parents; p; p = p->next) {
1240 if (p != commit->parents)
1241 strbuf_addch(sb, ' ');
1242 strbuf_add_unique_abbrev(sb, &p->item->object.oid,
1243 c->pretty_ctx->abbrev);
1245 return 1;
1246 case 'm': /* left/right/bottom */
1247 strbuf_addstr(sb, get_revision_mark(NULL, commit));
1248 return 1;
1249 case 'd':
1250 load_ref_decorations(NULL, DECORATE_SHORT_REFS);
1251 format_decorations(sb, commit, c->auto_color);
1252 return 1;
1253 case 'D':
1254 load_ref_decorations(NULL, DECORATE_SHORT_REFS);
1255 format_decorations_extended(sb, commit, c->auto_color, "", ", ", "");
1256 return 1;
1257 case 'S': /* tag/branch like --source */
1258 if (!(c->pretty_ctx->rev && c->pretty_ctx->rev->sources))
1259 return 0;
1260 slot = revision_sources_at(c->pretty_ctx->rev->sources, commit);
1261 if (!(slot && *slot))
1262 return 0;
1263 strbuf_addstr(sb, *slot);
1264 return 1;
1265 case 'g': /* reflog info */
1266 switch(placeholder[1]) {
1267 case 'd': /* reflog selector */
1268 case 'D':
1269 if (c->pretty_ctx->reflog_info)
1270 get_reflog_selector(sb,
1271 c->pretty_ctx->reflog_info,
1272 &c->pretty_ctx->date_mode,
1273 c->pretty_ctx->date_mode_explicit,
1274 (placeholder[1] == 'd'));
1275 return 2;
1276 case 's': /* reflog message */
1277 if (c->pretty_ctx->reflog_info)
1278 get_reflog_message(sb, c->pretty_ctx->reflog_info);
1279 return 2;
1280 case 'n':
1281 case 'N':
1282 case 'e':
1283 case 'E':
1284 return format_reflog_person(sb,
1285 placeholder[1],
1286 c->pretty_ctx->reflog_info,
1287 &c->pretty_ctx->date_mode);
1289 return 0; /* unknown %g placeholder */
1290 case 'N':
1291 if (c->pretty_ctx->notes_message) {
1292 strbuf_addstr(sb, c->pretty_ctx->notes_message);
1293 return 1;
1295 return 0;
1298 if (placeholder[0] == 'G') {
1299 if (!c->signature_check.result)
1300 check_commit_signature(c->commit, &(c->signature_check));
1301 switch (placeholder[1]) {
1302 case 'G':
1303 if (c->signature_check.gpg_output)
1304 strbuf_addstr(sb, c->signature_check.gpg_output);
1305 break;
1306 case '?':
1307 switch (c->signature_check.result) {
1308 case 'G':
1309 case 'B':
1310 case 'E':
1311 case 'U':
1312 case 'N':
1313 case 'X':
1314 case 'Y':
1315 case 'R':
1316 strbuf_addch(sb, c->signature_check.result);
1318 break;
1319 case 'S':
1320 if (c->signature_check.signer)
1321 strbuf_addstr(sb, c->signature_check.signer);
1322 break;
1323 case 'K':
1324 if (c->signature_check.key)
1325 strbuf_addstr(sb, c->signature_check.key);
1326 break;
1327 case 'F':
1328 if (c->signature_check.fingerprint)
1329 strbuf_addstr(sb, c->signature_check.fingerprint);
1330 break;
1331 case 'P':
1332 if (c->signature_check.primary_key_fingerprint)
1333 strbuf_addstr(sb, c->signature_check.primary_key_fingerprint);
1334 break;
1335 default:
1336 return 0;
1338 return 2;
1342 /* For the rest we have to parse the commit header. */
1343 if (!c->commit_header_parsed)
1344 parse_commit_header(c);
1346 switch (placeholder[0]) {
1347 case 'a': /* author ... */
1348 return format_person_part(sb, placeholder[1],
1349 msg + c->author.off, c->author.len,
1350 &c->pretty_ctx->date_mode);
1351 case 'c': /* committer ... */
1352 return format_person_part(sb, placeholder[1],
1353 msg + c->committer.off, c->committer.len,
1354 &c->pretty_ctx->date_mode);
1355 case 'e': /* encoding */
1356 if (c->commit_encoding)
1357 strbuf_addstr(sb, c->commit_encoding);
1358 return 1;
1359 case 'B': /* raw body */
1360 /* message_off is always left at the initial newline */
1361 strbuf_addstr(sb, msg + c->message_off + 1);
1362 return 1;
1365 /* Now we need to parse the commit message. */
1366 if (!c->commit_message_parsed)
1367 parse_commit_message(c);
1369 switch (placeholder[0]) {
1370 case 's': /* subject */
1371 format_subject(sb, msg + c->subject_off, " ");
1372 return 1;
1373 case 'f': /* sanitized subject */
1374 format_sanitized_subject(sb, msg + c->subject_off);
1375 return 1;
1376 case 'b': /* body */
1377 strbuf_addstr(sb, msg + c->body_off);
1378 return 1;
1381 if (skip_prefix(placeholder, "(trailers", &arg)) {
1382 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1383 struct string_list filter_list = STRING_LIST_INIT_NODUP;
1384 struct strbuf sepbuf = STRBUF_INIT;
1385 size_t ret = 0;
1387 opts.no_divider = 1;
1389 if (*arg == ':') {
1390 arg++;
1391 for (;;) {
1392 const char *argval;
1393 size_t arglen;
1395 if (match_placeholder_arg_value(arg, "key", &arg, &argval, &arglen)) {
1396 uintptr_t len = arglen;
1398 if (!argval)
1399 goto trailer_out;
1401 if (len && argval[len - 1] == ':')
1402 len--;
1403 string_list_append(&filter_list, argval)->util = (char *)len;
1405 opts.filter = format_trailer_match_cb;
1406 opts.filter_data = &filter_list;
1407 opts.only_trailers = 1;
1408 } else if (match_placeholder_arg_value(arg, "separator", &arg, &argval, &arglen)) {
1409 char *fmt;
1411 strbuf_reset(&sepbuf);
1412 fmt = xstrndup(argval, arglen);
1413 strbuf_expand(&sepbuf, fmt, strbuf_expand_literal_cb, NULL);
1414 free(fmt);
1415 opts.separator = &sepbuf;
1416 } else if (!match_placeholder_bool_arg(arg, "only", &arg, &opts.only_trailers) &&
1417 !match_placeholder_bool_arg(arg, "unfold", &arg, &opts.unfold) &&
1418 !match_placeholder_bool_arg(arg, "valueonly", &arg, &opts.value_only))
1419 break;
1422 if (*arg == ')') {
1423 format_trailers_from_commit(sb, msg + c->subject_off, &opts);
1424 ret = arg - placeholder + 1;
1426 trailer_out:
1427 string_list_clear(&filter_list, 0);
1428 strbuf_release(&sepbuf);
1429 return ret;
1432 return 0; /* unknown placeholder */
1435 static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */
1436 const char *placeholder,
1437 struct format_commit_context *c)
1439 struct strbuf local_sb = STRBUF_INIT;
1440 int total_consumed = 0, len, padding = c->padding;
1441 if (padding < 0) {
1442 const char *start = strrchr(sb->buf, '\n');
1443 int occupied;
1444 if (!start)
1445 start = sb->buf;
1446 occupied = utf8_strnwidth(start, -1, 1);
1447 occupied += c->pretty_ctx->graph_width;
1448 padding = (-padding) - occupied;
1450 while (1) {
1451 int modifier = *placeholder == 'C';
1452 int consumed = format_commit_one(&local_sb, placeholder, c);
1453 total_consumed += consumed;
1455 if (!modifier)
1456 break;
1458 placeholder += consumed;
1459 if (*placeholder != '%')
1460 break;
1461 placeholder++;
1462 total_consumed++;
1464 len = utf8_strnwidth(local_sb.buf, -1, 1);
1466 if (c->flush_type == flush_left_and_steal) {
1467 const char *ch = sb->buf + sb->len - 1;
1468 while (len > padding && ch > sb->buf) {
1469 const char *p;
1470 if (*ch == ' ') {
1471 ch--;
1472 padding++;
1473 continue;
1475 /* check for trailing ansi sequences */
1476 if (*ch != 'm')
1477 break;
1478 p = ch - 1;
1479 while (ch - p < 10 && *p != '\033')
1480 p--;
1481 if (*p != '\033' ||
1482 ch + 1 - p != display_mode_esc_sequence_len(p))
1483 break;
1485 * got a good ansi sequence, put it back to
1486 * local_sb as we're cutting sb
1488 strbuf_insert(&local_sb, 0, p, ch + 1 - p);
1489 ch = p - 1;
1491 strbuf_setlen(sb, ch + 1 - sb->buf);
1492 c->flush_type = flush_left;
1495 if (len > padding) {
1496 switch (c->truncate) {
1497 case trunc_left:
1498 strbuf_utf8_replace(&local_sb,
1499 0, len - (padding - 2),
1500 "..");
1501 break;
1502 case trunc_middle:
1503 strbuf_utf8_replace(&local_sb,
1504 padding / 2 - 1,
1505 len - (padding - 2),
1506 "..");
1507 break;
1508 case trunc_right:
1509 strbuf_utf8_replace(&local_sb,
1510 padding - 2, len - (padding - 2),
1511 "..");
1512 break;
1513 case trunc_none:
1514 break;
1516 strbuf_addbuf(sb, &local_sb);
1517 } else {
1518 int sb_len = sb->len, offset = 0;
1519 if (c->flush_type == flush_left)
1520 offset = padding - len;
1521 else if (c->flush_type == flush_both)
1522 offset = (padding - len) / 2;
1524 * we calculate padding in columns, now
1525 * convert it back to chars
1527 padding = padding - len + local_sb.len;
1528 strbuf_addchars(sb, ' ', padding);
1529 memcpy(sb->buf + sb_len + offset, local_sb.buf,
1530 local_sb.len);
1532 strbuf_release(&local_sb);
1533 c->flush_type = no_flush;
1534 return total_consumed;
1537 static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */
1538 const char *placeholder,
1539 void *context)
1541 int consumed;
1542 size_t orig_len;
1543 enum {
1544 NO_MAGIC,
1545 ADD_LF_BEFORE_NON_EMPTY,
1546 DEL_LF_BEFORE_EMPTY,
1547 ADD_SP_BEFORE_NON_EMPTY
1548 } magic = NO_MAGIC;
1550 switch (placeholder[0]) {
1551 case '-':
1552 magic = DEL_LF_BEFORE_EMPTY;
1553 break;
1554 case '+':
1555 magic = ADD_LF_BEFORE_NON_EMPTY;
1556 break;
1557 case ' ':
1558 magic = ADD_SP_BEFORE_NON_EMPTY;
1559 break;
1560 default:
1561 break;
1563 if (magic != NO_MAGIC)
1564 placeholder++;
1566 orig_len = sb->len;
1567 if (((struct format_commit_context *)context)->flush_type != no_flush)
1568 consumed = format_and_pad_commit(sb, placeholder, context);
1569 else
1570 consumed = format_commit_one(sb, placeholder, context);
1571 if (magic == NO_MAGIC)
1572 return consumed;
1574 if ((orig_len == sb->len) && magic == DEL_LF_BEFORE_EMPTY) {
1575 while (sb->len && sb->buf[sb->len - 1] == '\n')
1576 strbuf_setlen(sb, sb->len - 1);
1577 } else if (orig_len != sb->len) {
1578 if (magic == ADD_LF_BEFORE_NON_EMPTY)
1579 strbuf_insert(sb, orig_len, "\n", 1);
1580 else if (magic == ADD_SP_BEFORE_NON_EMPTY)
1581 strbuf_insert(sb, orig_len, " ", 1);
1583 return consumed + 1;
1586 static size_t userformat_want_item(struct strbuf *sb, const char *placeholder,
1587 void *context)
1589 struct userformat_want *w = context;
1591 if (*placeholder == '+' || *placeholder == '-' || *placeholder == ' ')
1592 placeholder++;
1594 switch (*placeholder) {
1595 case 'N':
1596 w->notes = 1;
1597 break;
1598 case 'S':
1599 w->source = 1;
1600 break;
1602 return 0;
1605 void userformat_find_requirements(const char *fmt, struct userformat_want *w)
1607 struct strbuf dummy = STRBUF_INIT;
1609 if (!fmt) {
1610 if (!user_format)
1611 return;
1612 fmt = user_format;
1614 strbuf_expand(&dummy, fmt, userformat_want_item, w);
1615 strbuf_release(&dummy);
1618 void repo_format_commit_message(struct repository *r,
1619 const struct commit *commit,
1620 const char *format, struct strbuf *sb,
1621 const struct pretty_print_context *pretty_ctx)
1623 struct format_commit_context context = {
1624 .commit = commit,
1625 .pretty_ctx = pretty_ctx,
1626 .wrap_start = sb->len
1628 const char *output_enc = pretty_ctx->output_encoding;
1629 const char *utf8 = "UTF-8";
1632 * convert a commit message to UTF-8 first
1633 * as far as 'format_commit_item' assumes it in UTF-8
1635 context.message = repo_logmsg_reencode(r, commit,
1636 &context.commit_encoding,
1637 utf8);
1639 strbuf_expand(sb, format, format_commit_item, &context);
1640 rewrap_message_tail(sb, &context, 0, 0, 0);
1642 /* then convert a commit message to an actual output encoding */
1643 if (output_enc) {
1644 if (same_encoding(utf8, output_enc))
1645 output_enc = NULL;
1646 } else {
1647 if (context.commit_encoding &&
1648 !same_encoding(context.commit_encoding, utf8))
1649 output_enc = context.commit_encoding;
1652 if (output_enc) {
1653 size_t outsz;
1654 char *out = reencode_string_len(sb->buf, sb->len,
1655 output_enc, utf8, &outsz);
1656 if (out)
1657 strbuf_attach(sb, out, outsz, outsz + 1);
1660 free(context.commit_encoding);
1661 repo_unuse_commit_buffer(r, commit, context.message);
1664 static void pp_header(struct pretty_print_context *pp,
1665 const char *encoding,
1666 const struct commit *commit,
1667 const char **msg_p,
1668 struct strbuf *sb)
1670 int parents_shown = 0;
1672 for (;;) {
1673 const char *name, *line = *msg_p;
1674 int linelen = get_one_line(*msg_p);
1676 if (!linelen)
1677 return;
1678 *msg_p += linelen;
1680 if (linelen == 1)
1681 /* End of header */
1682 return;
1684 if (pp->fmt == CMIT_FMT_RAW) {
1685 strbuf_add(sb, line, linelen);
1686 continue;
1689 if (starts_with(line, "parent ")) {
1690 if (linelen != the_hash_algo->hexsz + 8)
1691 die("bad parent line in commit");
1692 continue;
1695 if (!parents_shown) {
1696 unsigned num = commit_list_count(commit->parents);
1697 /* with enough slop */
1698 strbuf_grow(sb, num * (GIT_MAX_HEXSZ + 10) + 20);
1699 add_merge_info(pp, sb, commit);
1700 parents_shown = 1;
1704 * MEDIUM == DEFAULT shows only author with dates.
1705 * FULL shows both authors but not dates.
1706 * FULLER shows both authors and dates.
1708 if (skip_prefix(line, "author ", &name)) {
1709 strbuf_grow(sb, linelen + 80);
1710 pp_user_info(pp, "Author", sb, name, encoding);
1712 if (skip_prefix(line, "committer ", &name) &&
1713 (pp->fmt == CMIT_FMT_FULL || pp->fmt == CMIT_FMT_FULLER)) {
1714 strbuf_grow(sb, linelen + 80);
1715 pp_user_info(pp, "Commit", sb, name, encoding);
1720 void pp_title_line(struct pretty_print_context *pp,
1721 const char **msg_p,
1722 struct strbuf *sb,
1723 const char *encoding,
1724 int need_8bit_cte)
1726 static const int max_length = 78; /* per rfc2047 */
1727 struct strbuf title;
1729 strbuf_init(&title, 80);
1730 *msg_p = format_subject(&title, *msg_p,
1731 pp->preserve_subject ? "\n" : " ");
1733 strbuf_grow(sb, title.len + 1024);
1734 if (pp->print_email_subject) {
1735 if (pp->rev)
1736 fmt_output_email_subject(sb, pp->rev);
1737 if (needs_rfc2047_encoding(title.buf, title.len))
1738 add_rfc2047(sb, title.buf, title.len,
1739 encoding, RFC2047_SUBJECT);
1740 else
1741 strbuf_add_wrapped_bytes(sb, title.buf, title.len,
1742 -last_line_length(sb), 1, max_length);
1743 } else {
1744 strbuf_addbuf(sb, &title);
1746 strbuf_addch(sb, '\n');
1748 if (need_8bit_cte == 0) {
1749 int i;
1750 for (i = 0; i < pp->in_body_headers.nr; i++) {
1751 if (has_non_ascii(pp->in_body_headers.items[i].string)) {
1752 need_8bit_cte = 1;
1753 break;
1758 if (need_8bit_cte > 0) {
1759 const char *header_fmt =
1760 "MIME-Version: 1.0\n"
1761 "Content-Type: text/plain; charset=%s\n"
1762 "Content-Transfer-Encoding: 8bit\n";
1763 strbuf_addf(sb, header_fmt, encoding);
1765 if (pp->after_subject) {
1766 strbuf_addstr(sb, pp->after_subject);
1768 if (cmit_fmt_is_mail(pp->fmt)) {
1769 strbuf_addch(sb, '\n');
1772 if (pp->in_body_headers.nr) {
1773 int i;
1774 for (i = 0; i < pp->in_body_headers.nr; i++) {
1775 strbuf_addstr(sb, pp->in_body_headers.items[i].string);
1776 free(pp->in_body_headers.items[i].string);
1778 string_list_clear(&pp->in_body_headers, 0);
1779 strbuf_addch(sb, '\n');
1782 strbuf_release(&title);
1785 static int pp_utf8_width(const char *start, const char *end)
1787 int width = 0;
1788 size_t remain = end - start;
1790 while (remain) {
1791 int n = utf8_width(&start, &remain);
1792 if (n < 0 || !start)
1793 return -1;
1794 width += n;
1796 return width;
1799 static void strbuf_add_tabexpand(struct strbuf *sb, int tabwidth,
1800 const char *line, int linelen)
1802 const char *tab;
1804 while ((tab = memchr(line, '\t', linelen)) != NULL) {
1805 int width = pp_utf8_width(line, tab);
1808 * If it wasn't well-formed utf8, or it
1809 * had characters with badly defined
1810 * width (control characters etc), just
1811 * give up on trying to align things.
1813 if (width < 0)
1814 break;
1816 /* Output the data .. */
1817 strbuf_add(sb, line, tab - line);
1819 /* .. and the de-tabified tab */
1820 strbuf_addchars(sb, ' ', tabwidth - (width % tabwidth));
1822 /* Skip over the printed part .. */
1823 linelen -= tab + 1 - line;
1824 line = tab + 1;
1828 * Print out everything after the last tab without
1829 * worrying about width - there's nothing more to
1830 * align.
1832 strbuf_add(sb, line, linelen);
1836 * pp_handle_indent() prints out the intendation, and
1837 * the whole line (without the final newline), after
1838 * de-tabifying.
1840 static void pp_handle_indent(struct pretty_print_context *pp,
1841 struct strbuf *sb, int indent,
1842 const char *line, int linelen)
1844 strbuf_addchars(sb, ' ', indent);
1845 if (pp->expand_tabs_in_log)
1846 strbuf_add_tabexpand(sb, pp->expand_tabs_in_log, line, linelen);
1847 else
1848 strbuf_add(sb, line, linelen);
1851 static int is_mboxrd_from(const char *line, int len)
1854 * a line matching /^From $/ here would only have len == 4
1855 * at this point because is_empty_line would've trimmed all
1856 * trailing space
1858 return len > 4 && starts_with(line + strspn(line, ">"), "From ");
1861 void pp_remainder(struct pretty_print_context *pp,
1862 const char **msg_p,
1863 struct strbuf *sb,
1864 int indent)
1866 int first = 1;
1867 for (;;) {
1868 const char *line = *msg_p;
1869 int linelen = get_one_line(line);
1870 *msg_p += linelen;
1872 if (!linelen)
1873 break;
1875 if (is_blank_line(line, &linelen)) {
1876 if (first)
1877 continue;
1878 if (pp->fmt == CMIT_FMT_SHORT)
1879 break;
1881 first = 0;
1883 strbuf_grow(sb, linelen + indent + 20);
1884 if (indent)
1885 pp_handle_indent(pp, sb, indent, line, linelen);
1886 else if (pp->expand_tabs_in_log)
1887 strbuf_add_tabexpand(sb, pp->expand_tabs_in_log,
1888 line, linelen);
1889 else {
1890 if (pp->fmt == CMIT_FMT_MBOXRD &&
1891 is_mboxrd_from(line, linelen))
1892 strbuf_addch(sb, '>');
1894 strbuf_add(sb, line, linelen);
1896 strbuf_addch(sb, '\n');
1900 void pretty_print_commit(struct pretty_print_context *pp,
1901 const struct commit *commit,
1902 struct strbuf *sb)
1904 unsigned long beginning_of_body;
1905 int indent = 4;
1906 const char *msg;
1907 const char *reencoded;
1908 const char *encoding;
1909 int need_8bit_cte = pp->need_8bit_cte;
1911 if (pp->fmt == CMIT_FMT_USERFORMAT) {
1912 format_commit_message(commit, user_format, sb, pp);
1913 return;
1916 encoding = get_log_output_encoding();
1917 msg = reencoded = logmsg_reencode(commit, NULL, encoding);
1919 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
1920 indent = 0;
1923 * We need to check and emit Content-type: to mark it
1924 * as 8-bit if we haven't done so.
1926 if (cmit_fmt_is_mail(pp->fmt) && need_8bit_cte == 0) {
1927 int i, ch, in_body;
1929 for (in_body = i = 0; (ch = msg[i]); i++) {
1930 if (!in_body) {
1931 /* author could be non 7-bit ASCII but
1932 * the log may be so; skip over the
1933 * header part first.
1935 if (ch == '\n' && msg[i+1] == '\n')
1936 in_body = 1;
1938 else if (non_ascii(ch)) {
1939 need_8bit_cte = 1;
1940 break;
1945 pp_header(pp, encoding, commit, &msg, sb);
1946 if (pp->fmt != CMIT_FMT_ONELINE && !pp->print_email_subject) {
1947 strbuf_addch(sb, '\n');
1950 /* Skip excess blank lines at the beginning of body, if any... */
1951 msg = skip_blank_lines(msg);
1953 /* These formats treat the title line specially. */
1954 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
1955 pp_title_line(pp, &msg, sb, encoding, need_8bit_cte);
1957 beginning_of_body = sb->len;
1958 if (pp->fmt != CMIT_FMT_ONELINE)
1959 pp_remainder(pp, &msg, sb, indent);
1960 strbuf_rtrim(sb);
1962 /* Make sure there is an EOLN for the non-oneline case */
1963 if (pp->fmt != CMIT_FMT_ONELINE)
1964 strbuf_addch(sb, '\n');
1967 * The caller may append additional body text in e-mail
1968 * format. Make sure we did not strip the blank line
1969 * between the header and the body.
1971 if (cmit_fmt_is_mail(pp->fmt) && sb->len <= beginning_of_body)
1972 strbuf_addch(sb, '\n');
1974 unuse_commit_buffer(commit, reencoded);
1977 void pp_commit_easy(enum cmit_fmt fmt, const struct commit *commit,
1978 struct strbuf *sb)
1980 struct pretty_print_context pp = {0};
1981 pp.fmt = fmt;
1982 pretty_print_commit(&pp, commit, sb);