Merge branch 'ah/doc-pretty-color-auto-prefix' into maint
[alt-git.git] / pretty.c
blob6cc812c2c72c2281299c44fd81376441bb16a0ec
1 #include "cache.h"
2 #include "commit.h"
3 #include "utf8.h"
4 #include "diff.h"
5 #include "revision.h"
6 #include "string-list.h"
7 #include "mailmap.h"
8 #include "log-tree.h"
9 #include "notes.h"
10 #include "color.h"
11 #include "reflog-walk.h"
12 #include "gpg-interface.h"
13 #include "trailer.h"
15 static char *user_format;
16 static struct cmt_fmt_map {
17 const char *name;
18 enum cmit_fmt format;
19 int is_tformat;
20 int expand_tabs_in_log;
21 int is_alias;
22 const char *user_format;
23 } *commit_formats;
24 static size_t builtin_formats_len;
25 static size_t commit_formats_len;
26 static size_t commit_formats_alloc;
27 static struct cmt_fmt_map *find_commit_format(const char *sought);
29 int commit_format_is_empty(enum cmit_fmt fmt)
31 return fmt == CMIT_FMT_USERFORMAT && !*user_format;
34 static void save_user_format(struct rev_info *rev, const char *cp, int is_tformat)
36 free(user_format);
37 user_format = xstrdup(cp);
38 if (is_tformat)
39 rev->use_terminator = 1;
40 rev->commit_format = CMIT_FMT_USERFORMAT;
43 static int git_pretty_formats_config(const char *var, const char *value, void *cb)
45 struct cmt_fmt_map *commit_format = NULL;
46 const char *name;
47 const char *fmt;
48 int i;
50 if (!skip_prefix(var, "pretty.", &name))
51 return 0;
53 for (i = 0; i < builtin_formats_len; i++) {
54 if (!strcmp(commit_formats[i].name, name))
55 return 0;
58 for (i = builtin_formats_len; i < commit_formats_len; i++) {
59 if (!strcmp(commit_formats[i].name, name)) {
60 commit_format = &commit_formats[i];
61 break;
65 if (!commit_format) {
66 ALLOC_GROW(commit_formats, commit_formats_len+1,
67 commit_formats_alloc);
68 commit_format = &commit_formats[commit_formats_len];
69 memset(commit_format, 0, sizeof(*commit_format));
70 commit_formats_len++;
73 commit_format->name = xstrdup(name);
74 commit_format->format = CMIT_FMT_USERFORMAT;
75 if (git_config_string(&fmt, var, value))
76 return -1;
78 if (skip_prefix(fmt, "format:", &fmt))
79 commit_format->is_tformat = 0;
80 else if (skip_prefix(fmt, "tformat:", &fmt) || strchr(fmt, '%'))
81 commit_format->is_tformat = 1;
82 else
83 commit_format->is_alias = 1;
84 commit_format->user_format = fmt;
86 return 0;
89 static void setup_commit_formats(void)
91 struct cmt_fmt_map builtin_formats[] = {
92 { "raw", CMIT_FMT_RAW, 0, 0 },
93 { "medium", CMIT_FMT_MEDIUM, 0, 8 },
94 { "short", CMIT_FMT_SHORT, 0, 0 },
95 { "email", CMIT_FMT_EMAIL, 0, 0 },
96 { "mboxrd", CMIT_FMT_MBOXRD, 0, 0 },
97 { "fuller", CMIT_FMT_FULLER, 0, 8 },
98 { "full", CMIT_FMT_FULL, 0, 8 },
99 { "oneline", CMIT_FMT_ONELINE, 1, 0 }
101 commit_formats_len = ARRAY_SIZE(builtin_formats);
102 builtin_formats_len = commit_formats_len;
103 ALLOC_GROW(commit_formats, commit_formats_len, commit_formats_alloc);
104 memcpy(commit_formats, builtin_formats,
105 sizeof(*builtin_formats)*ARRAY_SIZE(builtin_formats));
107 git_config(git_pretty_formats_config, NULL);
110 static struct cmt_fmt_map *find_commit_format_recursive(const char *sought,
111 const char *original,
112 int num_redirections)
114 struct cmt_fmt_map *found = NULL;
115 size_t found_match_len = 0;
116 int i;
118 if (num_redirections >= commit_formats_len)
119 die("invalid --pretty format: "
120 "'%s' references an alias which points to itself",
121 original);
123 for (i = 0; i < commit_formats_len; i++) {
124 size_t match_len;
126 if (!starts_with(commit_formats[i].name, sought))
127 continue;
129 match_len = strlen(commit_formats[i].name);
130 if (found == NULL || found_match_len > match_len) {
131 found = &commit_formats[i];
132 found_match_len = match_len;
136 if (found && found->is_alias) {
137 found = find_commit_format_recursive(found->user_format,
138 original,
139 num_redirections+1);
142 return found;
145 static struct cmt_fmt_map *find_commit_format(const char *sought)
147 if (!commit_formats)
148 setup_commit_formats();
150 return find_commit_format_recursive(sought, sought, 0);
153 void get_commit_format(const char *arg, struct rev_info *rev)
155 struct cmt_fmt_map *commit_format;
157 rev->use_terminator = 0;
158 if (!arg) {
159 rev->commit_format = CMIT_FMT_DEFAULT;
160 return;
162 if (skip_prefix(arg, "format:", &arg)) {
163 save_user_format(rev, arg, 0);
164 return;
167 if (!*arg || skip_prefix(arg, "tformat:", &arg) || strchr(arg, '%')) {
168 save_user_format(rev, arg, 1);
169 return;
172 commit_format = find_commit_format(arg);
173 if (!commit_format)
174 die("invalid --pretty format: %s", arg);
176 rev->commit_format = commit_format->format;
177 rev->use_terminator = commit_format->is_tformat;
178 rev->expand_tabs_in_log_default = commit_format->expand_tabs_in_log;
179 if (commit_format->format == CMIT_FMT_USERFORMAT) {
180 save_user_format(rev, commit_format->user_format,
181 commit_format->is_tformat);
186 * Generic support for pretty-printing the header
188 static int get_one_line(const char *msg)
190 int ret = 0;
192 for (;;) {
193 char c = *msg++;
194 if (!c)
195 break;
196 ret++;
197 if (c == '\n')
198 break;
200 return ret;
203 /* High bit set, or ISO-2022-INT */
204 static int non_ascii(int ch)
206 return !isascii(ch) || ch == '\033';
209 int has_non_ascii(const char *s)
211 int ch;
212 if (!s)
213 return 0;
214 while ((ch = *s++) != '\0') {
215 if (non_ascii(ch))
216 return 1;
218 return 0;
221 static int is_rfc822_special(char ch)
223 switch (ch) {
224 case '(':
225 case ')':
226 case '<':
227 case '>':
228 case '[':
229 case ']':
230 case ':':
231 case ';':
232 case '@':
233 case ',':
234 case '.':
235 case '"':
236 case '\\':
237 return 1;
238 default:
239 return 0;
243 static int needs_rfc822_quoting(const char *s, int len)
245 int i;
246 for (i = 0; i < len; i++)
247 if (is_rfc822_special(s[i]))
248 return 1;
249 return 0;
252 static int last_line_length(struct strbuf *sb)
254 int i;
256 /* How many bytes are already used on the last line? */
257 for (i = sb->len - 1; i >= 0; i--)
258 if (sb->buf[i] == '\n')
259 break;
260 return sb->len - (i + 1);
263 static void add_rfc822_quoted(struct strbuf *out, const char *s, int len)
265 int i;
267 /* just a guess, we may have to also backslash-quote */
268 strbuf_grow(out, len + 2);
270 strbuf_addch(out, '"');
271 for (i = 0; i < len; i++) {
272 switch (s[i]) {
273 case '"':
274 case '\\':
275 strbuf_addch(out, '\\');
276 /* fall through */
277 default:
278 strbuf_addch(out, s[i]);
281 strbuf_addch(out, '"');
284 enum rfc2047_type {
285 RFC2047_SUBJECT,
286 RFC2047_ADDRESS
289 static int is_rfc2047_special(char ch, enum rfc2047_type type)
292 * rfc2047, section 4.2:
294 * 8-bit values which correspond to printable ASCII characters other
295 * than "=", "?", and "_" (underscore), MAY be represented as those
296 * characters. (But see section 5 for restrictions.) In
297 * particular, SPACE and TAB MUST NOT be represented as themselves
298 * within encoded words.
302 * rule out non-ASCII characters and non-printable characters (the
303 * non-ASCII check should be redundant as isprint() is not localized
304 * and only knows about ASCII, but be defensive about that)
306 if (non_ascii(ch) || !isprint(ch))
307 return 1;
310 * rule out special printable characters (' ' should be the only
311 * whitespace character considered printable, but be defensive and use
312 * isspace())
314 if (isspace(ch) || ch == '=' || ch == '?' || ch == '_')
315 return 1;
318 * rfc2047, section 5.3:
320 * As a replacement for a 'word' entity within a 'phrase', for example,
321 * one that precedes an address in a From, To, or Cc header. The ABNF
322 * definition for 'phrase' from RFC 822 thus becomes:
324 * phrase = 1*( encoded-word / word )
326 * In this case the set of characters that may be used in a "Q"-encoded
327 * 'encoded-word' is restricted to: <upper and lower case ASCII
328 * letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
329 * (underscore, ASCII 95.)>. An 'encoded-word' that appears within a
330 * 'phrase' MUST be separated from any adjacent 'word', 'text' or
331 * 'special' by 'linear-white-space'.
334 if (type != RFC2047_ADDRESS)
335 return 0;
337 /* '=' and '_' are special cases and have been checked above */
338 return !(isalnum(ch) || ch == '!' || ch == '*' || ch == '+' || ch == '-' || ch == '/');
341 static int needs_rfc2047_encoding(const char *line, int len,
342 enum rfc2047_type type)
344 int i;
346 for (i = 0; i < len; i++) {
347 int ch = line[i];
348 if (non_ascii(ch) || ch == '\n')
349 return 1;
350 if ((i + 1 < len) && (ch == '=' && line[i+1] == '?'))
351 return 1;
354 return 0;
357 static void add_rfc2047(struct strbuf *sb, const char *line, size_t len,
358 const char *encoding, enum rfc2047_type type)
360 static const int max_encoded_length = 76; /* per rfc2047 */
361 int i;
362 int line_len = last_line_length(sb);
364 strbuf_grow(sb, len * 3 + strlen(encoding) + 100);
365 strbuf_addf(sb, "=?%s?q?", encoding);
366 line_len += strlen(encoding) + 5; /* 5 for =??q? */
368 while (len) {
370 * RFC 2047, section 5 (3):
372 * Each 'encoded-word' MUST represent an integral number of
373 * characters. A multi-octet character may not be split across
374 * adjacent 'encoded- word's.
376 const unsigned char *p = (const unsigned char *)line;
377 int chrlen = mbs_chrlen(&line, &len, encoding);
378 int is_special = (chrlen > 1) || is_rfc2047_special(*p, type);
380 /* "=%02X" * chrlen, or the byte itself */
381 const char *encoded_fmt = is_special ? "=%02X" : "%c";
382 int encoded_len = is_special ? 3 * chrlen : 1;
385 * According to RFC 2047, we could encode the special character
386 * ' ' (space) with '_' (underscore) for readability. But many
387 * programs do not understand this and just leave the
388 * underscore in place. Thus, we do nothing special here, which
389 * causes ' ' to be encoded as '=20', avoiding this problem.
392 if (line_len + encoded_len + 2 > max_encoded_length) {
393 /* It won't fit with trailing "?=" --- break the line */
394 strbuf_addf(sb, "?=\n =?%s?q?", encoding);
395 line_len = strlen(encoding) + 5 + 1; /* =??q? plus SP */
398 for (i = 0; i < chrlen; i++)
399 strbuf_addf(sb, encoded_fmt, p[i]);
400 line_len += encoded_len;
402 strbuf_addstr(sb, "?=");
405 const char *show_ident_date(const struct ident_split *ident,
406 const struct date_mode *mode)
408 unsigned long date = 0;
409 long tz = 0;
411 if (ident->date_begin && ident->date_end)
412 date = strtoul(ident->date_begin, NULL, 10);
413 if (date_overflows(date))
414 date = 0;
415 else {
416 if (ident->tz_begin && ident->tz_end)
417 tz = strtol(ident->tz_begin, NULL, 10);
418 if (tz >= INT_MAX || tz <= INT_MIN)
419 tz = 0;
421 return show_date(date, tz, mode);
424 void pp_user_info(struct pretty_print_context *pp,
425 const char *what, struct strbuf *sb,
426 const char *line, const char *encoding)
428 struct ident_split ident;
429 char *line_end;
430 const char *mailbuf, *namebuf;
431 size_t namelen, maillen;
432 int max_length = 78; /* per rfc2822 */
434 if (pp->fmt == CMIT_FMT_ONELINE)
435 return;
437 line_end = strchrnul(line, '\n');
438 if (split_ident_line(&ident, line, line_end - line))
439 return;
441 mailbuf = ident.mail_begin;
442 maillen = ident.mail_end - ident.mail_begin;
443 namebuf = ident.name_begin;
444 namelen = ident.name_end - ident.name_begin;
446 if (pp->mailmap)
447 map_user(pp->mailmap, &mailbuf, &maillen, &namebuf, &namelen);
449 if (cmit_fmt_is_mail(pp->fmt)) {
450 if (pp->from_ident && ident_cmp(pp->from_ident, &ident)) {
451 struct strbuf buf = STRBUF_INIT;
453 strbuf_addstr(&buf, "From: ");
454 strbuf_add(&buf, namebuf, namelen);
455 strbuf_addstr(&buf, " <");
456 strbuf_add(&buf, mailbuf, maillen);
457 strbuf_addstr(&buf, ">\n");
458 string_list_append(&pp->in_body_headers,
459 strbuf_detach(&buf, NULL));
461 mailbuf = pp->from_ident->mail_begin;
462 maillen = pp->from_ident->mail_end - mailbuf;
463 namebuf = pp->from_ident->name_begin;
464 namelen = pp->from_ident->name_end - namebuf;
467 strbuf_addstr(sb, "From: ");
468 if (needs_rfc2047_encoding(namebuf, namelen, RFC2047_ADDRESS)) {
469 add_rfc2047(sb, namebuf, namelen,
470 encoding, RFC2047_ADDRESS);
471 max_length = 76; /* per rfc2047 */
472 } else if (needs_rfc822_quoting(namebuf, namelen)) {
473 struct strbuf quoted = STRBUF_INIT;
474 add_rfc822_quoted(&quoted, namebuf, namelen);
475 strbuf_add_wrapped_bytes(sb, quoted.buf, quoted.len,
476 -6, 1, max_length);
477 strbuf_release(&quoted);
478 } else {
479 strbuf_add_wrapped_bytes(sb, namebuf, namelen,
480 -6, 1, max_length);
483 if (max_length <
484 last_line_length(sb) + strlen(" <") + maillen + strlen(">"))
485 strbuf_addch(sb, '\n');
486 strbuf_addf(sb, " <%.*s>\n", (int)maillen, mailbuf);
487 } else {
488 strbuf_addf(sb, "%s: %.*s%.*s <%.*s>\n", what,
489 (pp->fmt == CMIT_FMT_FULLER) ? 4 : 0, " ",
490 (int)namelen, namebuf, (int)maillen, mailbuf);
493 switch (pp->fmt) {
494 case CMIT_FMT_MEDIUM:
495 strbuf_addf(sb, "Date: %s\n",
496 show_ident_date(&ident, &pp->date_mode));
497 break;
498 case CMIT_FMT_EMAIL:
499 case CMIT_FMT_MBOXRD:
500 strbuf_addf(sb, "Date: %s\n",
501 show_ident_date(&ident, DATE_MODE(RFC2822)));
502 break;
503 case CMIT_FMT_FULLER:
504 strbuf_addf(sb, "%sDate: %s\n", what,
505 show_ident_date(&ident, &pp->date_mode));
506 break;
507 default:
508 /* notin' */
509 break;
513 static int is_blank_line(const char *line, int *len_p)
515 int len = *len_p;
516 while (len && isspace(line[len - 1]))
517 len--;
518 *len_p = len;
519 return !len;
522 const char *skip_blank_lines(const char *msg)
524 for (;;) {
525 int linelen = get_one_line(msg);
526 int ll = linelen;
527 if (!linelen)
528 break;
529 if (!is_blank_line(msg, &ll))
530 break;
531 msg += linelen;
533 return msg;
536 static void add_merge_info(const struct pretty_print_context *pp,
537 struct strbuf *sb, const struct commit *commit)
539 struct commit_list *parent = commit->parents;
541 if ((pp->fmt == CMIT_FMT_ONELINE) || (cmit_fmt_is_mail(pp->fmt)) ||
542 !parent || !parent->next)
543 return;
545 strbuf_addstr(sb, "Merge:");
547 while (parent) {
548 struct object_id *oidp = &parent->item->object.oid;
549 strbuf_addch(sb, ' ');
550 if (pp->abbrev)
551 strbuf_add_unique_abbrev(sb, oidp->hash, pp->abbrev);
552 else
553 strbuf_addstr(sb, oid_to_hex(oidp));
554 parent = parent->next;
556 strbuf_addch(sb, '\n');
559 static char *get_header(const char *msg, const char *key)
561 size_t len;
562 const char *v = find_commit_header(msg, key, &len);
563 return v ? xmemdupz(v, len) : NULL;
566 static char *replace_encoding_header(char *buf, const char *encoding)
568 struct strbuf tmp = STRBUF_INIT;
569 size_t start, len;
570 char *cp = buf;
572 /* guess if there is an encoding header before a \n\n */
573 while (!starts_with(cp, "encoding ")) {
574 cp = strchr(cp, '\n');
575 if (!cp || *++cp == '\n')
576 return buf;
578 start = cp - buf;
579 cp = strchr(cp, '\n');
580 if (!cp)
581 return buf; /* should not happen but be defensive */
582 len = cp + 1 - (buf + start);
584 strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
585 if (is_encoding_utf8(encoding)) {
586 /* we have re-coded to UTF-8; drop the header */
587 strbuf_remove(&tmp, start, len);
588 } else {
589 /* just replaces XXXX in 'encoding XXXX\n' */
590 strbuf_splice(&tmp, start + strlen("encoding "),
591 len - strlen("encoding \n"),
592 encoding, strlen(encoding));
594 return strbuf_detach(&tmp, NULL);
597 const char *logmsg_reencode(const struct commit *commit,
598 char **commit_encoding,
599 const char *output_encoding)
601 static const char *utf8 = "UTF-8";
602 const char *use_encoding;
603 char *encoding;
604 const char *msg = get_commit_buffer(commit, NULL);
605 char *out;
607 if (!output_encoding || !*output_encoding) {
608 if (commit_encoding)
609 *commit_encoding = get_header(msg, "encoding");
610 return msg;
612 encoding = get_header(msg, "encoding");
613 if (commit_encoding)
614 *commit_encoding = encoding;
615 use_encoding = encoding ? encoding : utf8;
616 if (same_encoding(use_encoding, output_encoding)) {
618 * No encoding work to be done. If we have no encoding header
619 * at all, then there's nothing to do, and we can return the
620 * message verbatim (whether newly allocated or not).
622 if (!encoding)
623 return msg;
626 * Otherwise, we still want to munge the encoding header in the
627 * result, which will be done by modifying the buffer. If we
628 * are using a fresh copy, we can reuse it. But if we are using
629 * the cached copy from get_commit_buffer, we need to duplicate it
630 * to avoid munging the cached copy.
632 if (msg == get_cached_commit_buffer(commit, NULL))
633 out = xstrdup(msg);
634 else
635 out = (char *)msg;
637 else {
639 * There's actual encoding work to do. Do the reencoding, which
640 * still leaves the header to be replaced in the next step. At
641 * this point, we are done with msg. If we allocated a fresh
642 * copy, we can free it.
644 out = reencode_string(msg, output_encoding, use_encoding);
645 if (out)
646 unuse_commit_buffer(commit, msg);
650 * This replacement actually consumes the buffer we hand it, so we do
651 * not have to worry about freeing the old "out" here.
653 if (out)
654 out = replace_encoding_header(out, output_encoding);
656 if (!commit_encoding)
657 free(encoding);
659 * If the re-encoding failed, out might be NULL here; in that
660 * case we just return the commit message verbatim.
662 return out ? out : msg;
665 static int mailmap_name(const char **email, size_t *email_len,
666 const char **name, size_t *name_len)
668 static struct string_list *mail_map;
669 if (!mail_map) {
670 mail_map = xcalloc(1, sizeof(*mail_map));
671 read_mailmap(mail_map, NULL);
673 return mail_map->nr && map_user(mail_map, email, email_len, name, name_len);
676 static size_t format_person_part(struct strbuf *sb, char part,
677 const char *msg, int len,
678 const struct date_mode *dmode)
680 /* currently all placeholders have same length */
681 const int placeholder_len = 2;
682 struct ident_split s;
683 const char *name, *mail;
684 size_t maillen, namelen;
686 if (split_ident_line(&s, msg, len) < 0)
687 goto skip;
689 name = s.name_begin;
690 namelen = s.name_end - s.name_begin;
691 mail = s.mail_begin;
692 maillen = s.mail_end - s.mail_begin;
694 if (part == 'N' || part == 'E') /* mailmap lookup */
695 mailmap_name(&mail, &maillen, &name, &namelen);
696 if (part == 'n' || part == 'N') { /* name */
697 strbuf_add(sb, name, namelen);
698 return placeholder_len;
700 if (part == 'e' || part == 'E') { /* email */
701 strbuf_add(sb, mail, maillen);
702 return placeholder_len;
705 if (!s.date_begin)
706 goto skip;
708 if (part == 't') { /* date, UNIX timestamp */
709 strbuf_add(sb, s.date_begin, s.date_end - s.date_begin);
710 return placeholder_len;
713 switch (part) {
714 case 'd': /* date */
715 strbuf_addstr(sb, show_ident_date(&s, dmode));
716 return placeholder_len;
717 case 'D': /* date, RFC2822 style */
718 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RFC2822)));
719 return placeholder_len;
720 case 'r': /* date, relative */
721 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RELATIVE)));
722 return placeholder_len;
723 case 'i': /* date, ISO 8601-like */
724 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601)));
725 return placeholder_len;
726 case 'I': /* date, ISO 8601 strict */
727 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601_STRICT)));
728 return placeholder_len;
731 skip:
733 * reading from either a bogus commit, or a reflog entry with
734 * %gn, %ge, etc.; 'sb' cannot be updated, but we still need
735 * to compute a valid return value.
737 if (part == 'n' || part == 'e' || part == 't' || part == 'd'
738 || part == 'D' || part == 'r' || part == 'i')
739 return placeholder_len;
741 return 0; /* unknown placeholder */
744 struct chunk {
745 size_t off;
746 size_t len;
749 enum flush_type {
750 no_flush,
751 flush_right,
752 flush_left,
753 flush_left_and_steal,
754 flush_both
757 enum trunc_type {
758 trunc_none,
759 trunc_left,
760 trunc_middle,
761 trunc_right
764 struct format_commit_context {
765 const struct commit *commit;
766 const struct pretty_print_context *pretty_ctx;
767 unsigned commit_header_parsed:1;
768 unsigned commit_message_parsed:1;
769 struct signature_check signature_check;
770 enum flush_type flush_type;
771 enum trunc_type truncate;
772 const char *message;
773 char *commit_encoding;
774 size_t width, indent1, indent2;
775 int auto_color;
776 int padding;
778 /* These offsets are relative to the start of the commit message. */
779 struct chunk author;
780 struct chunk committer;
781 size_t message_off;
782 size_t subject_off;
783 size_t body_off;
785 /* The following ones are relative to the result struct strbuf. */
786 size_t wrap_start;
789 static void parse_commit_header(struct format_commit_context *context)
791 const char *msg = context->message;
792 int i;
794 for (i = 0; msg[i]; i++) {
795 const char *name;
796 int eol;
797 for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
798 ; /* do nothing */
800 if (i == eol) {
801 break;
802 } else if (skip_prefix(msg + i, "author ", &name)) {
803 context->author.off = name - msg;
804 context->author.len = msg + eol - name;
805 } else if (skip_prefix(msg + i, "committer ", &name)) {
806 context->committer.off = name - msg;
807 context->committer.len = msg + eol - name;
809 i = eol;
811 context->message_off = i;
812 context->commit_header_parsed = 1;
815 static int istitlechar(char c)
817 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
818 (c >= '0' && c <= '9') || c == '.' || c == '_';
821 static void format_sanitized_subject(struct strbuf *sb, const char *msg)
823 size_t trimlen;
824 size_t start_len = sb->len;
825 int space = 2;
827 for (; *msg && *msg != '\n'; msg++) {
828 if (istitlechar(*msg)) {
829 if (space == 1)
830 strbuf_addch(sb, '-');
831 space = 0;
832 strbuf_addch(sb, *msg);
833 if (*msg == '.')
834 while (*(msg+1) == '.')
835 msg++;
836 } else
837 space |= 1;
840 /* trim any trailing '.' or '-' characters */
841 trimlen = 0;
842 while (sb->len - trimlen > start_len &&
843 (sb->buf[sb->len - 1 - trimlen] == '.'
844 || sb->buf[sb->len - 1 - trimlen] == '-'))
845 trimlen++;
846 strbuf_remove(sb, sb->len - trimlen, trimlen);
849 const char *format_subject(struct strbuf *sb, const char *msg,
850 const char *line_separator)
852 int first = 1;
854 for (;;) {
855 const char *line = msg;
856 int linelen = get_one_line(line);
858 msg += linelen;
859 if (!linelen || is_blank_line(line, &linelen))
860 break;
862 if (!sb)
863 continue;
864 strbuf_grow(sb, linelen + 2);
865 if (!first)
866 strbuf_addstr(sb, line_separator);
867 strbuf_add(sb, line, linelen);
868 first = 0;
870 return msg;
873 static void format_trailers(struct strbuf *sb, const char *msg)
875 struct trailer_info info;
877 trailer_info_get(&info, msg);
878 strbuf_add(sb, info.trailer_start,
879 info.trailer_end - info.trailer_start);
880 trailer_info_release(&info);
883 static void parse_commit_message(struct format_commit_context *c)
885 const char *msg = c->message + c->message_off;
886 const char *start = c->message;
888 msg = skip_blank_lines(msg);
889 c->subject_off = msg - start;
891 msg = format_subject(NULL, msg, NULL);
892 msg = skip_blank_lines(msg);
893 c->body_off = msg - start;
895 c->commit_message_parsed = 1;
898 static void strbuf_wrap(struct strbuf *sb, size_t pos,
899 size_t width, size_t indent1, size_t indent2)
901 struct strbuf tmp = STRBUF_INIT;
903 if (pos)
904 strbuf_add(&tmp, sb->buf, pos);
905 strbuf_add_wrapped_text(&tmp, sb->buf + pos,
906 (int) indent1, (int) indent2, (int) width);
907 strbuf_swap(&tmp, sb);
908 strbuf_release(&tmp);
911 static void rewrap_message_tail(struct strbuf *sb,
912 struct format_commit_context *c,
913 size_t new_width, size_t new_indent1,
914 size_t new_indent2)
916 if (c->width == new_width && c->indent1 == new_indent1 &&
917 c->indent2 == new_indent2)
918 return;
919 if (c->wrap_start < sb->len)
920 strbuf_wrap(sb, c->wrap_start, c->width, c->indent1, c->indent2);
921 c->wrap_start = sb->len;
922 c->width = new_width;
923 c->indent1 = new_indent1;
924 c->indent2 = new_indent2;
927 static int format_reflog_person(struct strbuf *sb,
928 char part,
929 struct reflog_walk_info *log,
930 const struct date_mode *dmode)
932 const char *ident;
934 if (!log)
935 return 2;
937 ident = get_reflog_ident(log);
938 if (!ident)
939 return 2;
941 return format_person_part(sb, part, ident, strlen(ident), dmode);
944 static size_t parse_color(struct strbuf *sb, /* in UTF-8 */
945 const char *placeholder,
946 struct format_commit_context *c)
948 const char *rest = placeholder;
950 if (placeholder[1] == '(') {
951 const char *begin = placeholder + 2;
952 const char *end = strchr(begin, ')');
953 char color[COLOR_MAXLEN];
955 if (!end)
956 return 0;
957 if (skip_prefix(begin, "auto,", &begin)) {
958 if (!want_color(c->pretty_ctx->color))
959 return end - placeholder + 1;
961 if (color_parse_mem(begin, end - begin, color) < 0)
962 die(_("unable to parse --pretty format"));
963 strbuf_addstr(sb, color);
964 return end - placeholder + 1;
966 if (skip_prefix(placeholder + 1, "red", &rest))
967 strbuf_addstr(sb, GIT_COLOR_RED);
968 else if (skip_prefix(placeholder + 1, "green", &rest))
969 strbuf_addstr(sb, GIT_COLOR_GREEN);
970 else if (skip_prefix(placeholder + 1, "blue", &rest))
971 strbuf_addstr(sb, GIT_COLOR_BLUE);
972 else if (skip_prefix(placeholder + 1, "reset", &rest))
973 strbuf_addstr(sb, GIT_COLOR_RESET);
974 return rest - placeholder;
977 static size_t parse_padding_placeholder(struct strbuf *sb,
978 const char *placeholder,
979 struct format_commit_context *c)
981 const char *ch = placeholder;
982 enum flush_type flush_type;
983 int to_column = 0;
985 switch (*ch++) {
986 case '<':
987 flush_type = flush_right;
988 break;
989 case '>':
990 if (*ch == '<') {
991 flush_type = flush_both;
992 ch++;
993 } else if (*ch == '>') {
994 flush_type = flush_left_and_steal;
995 ch++;
996 } else
997 flush_type = flush_left;
998 break;
999 default:
1000 return 0;
1003 /* the next value means "wide enough to that column" */
1004 if (*ch == '|') {
1005 to_column = 1;
1006 ch++;
1009 if (*ch == '(') {
1010 const char *start = ch + 1;
1011 const char *end = start + strcspn(start, ",)");
1012 char *next;
1013 int width;
1014 if (!end || end == start)
1015 return 0;
1016 width = strtol(start, &next, 10);
1017 if (next == start || width == 0)
1018 return 0;
1019 if (width < 0) {
1020 if (to_column)
1021 width += term_columns();
1022 if (width < 0)
1023 return 0;
1025 c->padding = to_column ? -width : width;
1026 c->flush_type = flush_type;
1028 if (*end == ',') {
1029 start = end + 1;
1030 end = strchr(start, ')');
1031 if (!end || end == start)
1032 return 0;
1033 if (starts_with(start, "trunc)"))
1034 c->truncate = trunc_right;
1035 else if (starts_with(start, "ltrunc)"))
1036 c->truncate = trunc_left;
1037 else if (starts_with(start, "mtrunc)"))
1038 c->truncate = trunc_middle;
1039 else
1040 return 0;
1041 } else
1042 c->truncate = trunc_none;
1044 return end - placeholder + 1;
1046 return 0;
1049 static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
1050 const char *placeholder,
1051 void *context)
1053 struct format_commit_context *c = context;
1054 const struct commit *commit = c->commit;
1055 const char *msg = c->message;
1056 struct commit_list *p;
1057 int ch;
1059 /* these are independent of the commit */
1060 switch (placeholder[0]) {
1061 case 'C':
1062 if (starts_with(placeholder + 1, "(auto)")) {
1063 c->auto_color = want_color(c->pretty_ctx->color);
1064 if (c->auto_color && sb->len)
1065 strbuf_addstr(sb, GIT_COLOR_RESET);
1066 return 7; /* consumed 7 bytes, "C(auto)" */
1067 } else {
1068 int ret = parse_color(sb, placeholder, c);
1069 if (ret)
1070 c->auto_color = 0;
1072 * Otherwise, we decided to treat %C<unknown>
1073 * as a literal string, and the previous
1074 * %C(auto) is still valid.
1076 return ret;
1078 case 'n': /* newline */
1079 strbuf_addch(sb, '\n');
1080 return 1;
1081 case 'x':
1082 /* %x00 == NUL, %x0a == LF, etc. */
1083 ch = hex2chr(placeholder + 1);
1084 if (ch < 0)
1085 return 0;
1086 strbuf_addch(sb, ch);
1087 return 3;
1088 case 'w':
1089 if (placeholder[1] == '(') {
1090 unsigned long width = 0, indent1 = 0, indent2 = 0;
1091 char *next;
1092 const char *start = placeholder + 2;
1093 const char *end = strchr(start, ')');
1094 if (!end)
1095 return 0;
1096 if (end > start) {
1097 width = strtoul(start, &next, 10);
1098 if (*next == ',') {
1099 indent1 = strtoul(next + 1, &next, 10);
1100 if (*next == ',') {
1101 indent2 = strtoul(next + 1,
1102 &next, 10);
1105 if (*next != ')')
1106 return 0;
1108 rewrap_message_tail(sb, c, width, indent1, indent2);
1109 return end - placeholder + 1;
1110 } else
1111 return 0;
1113 case '<':
1114 case '>':
1115 return parse_padding_placeholder(sb, placeholder, c);
1118 /* these depend on the commit */
1119 if (!commit->object.parsed)
1120 parse_object(commit->object.oid.hash);
1122 switch (placeholder[0]) {
1123 case 'H': /* commit hash */
1124 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1125 strbuf_addstr(sb, oid_to_hex(&commit->object.oid));
1126 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1127 return 1;
1128 case 'h': /* abbreviated commit hash */
1129 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1130 strbuf_add_unique_abbrev(sb, commit->object.oid.hash,
1131 c->pretty_ctx->abbrev);
1132 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1133 return 1;
1134 case 'T': /* tree hash */
1135 strbuf_addstr(sb, oid_to_hex(&commit->tree->object.oid));
1136 return 1;
1137 case 't': /* abbreviated tree hash */
1138 strbuf_add_unique_abbrev(sb, commit->tree->object.oid.hash,
1139 c->pretty_ctx->abbrev);
1140 return 1;
1141 case 'P': /* parent hashes */
1142 for (p = commit->parents; p; p = p->next) {
1143 if (p != commit->parents)
1144 strbuf_addch(sb, ' ');
1145 strbuf_addstr(sb, oid_to_hex(&p->item->object.oid));
1147 return 1;
1148 case 'p': /* abbreviated parent hashes */
1149 for (p = commit->parents; p; p = p->next) {
1150 if (p != commit->parents)
1151 strbuf_addch(sb, ' ');
1152 strbuf_add_unique_abbrev(sb, p->item->object.oid.hash,
1153 c->pretty_ctx->abbrev);
1155 return 1;
1156 case 'm': /* left/right/bottom */
1157 strbuf_addstr(sb, get_revision_mark(NULL, commit));
1158 return 1;
1159 case 'd':
1160 load_ref_decorations(DECORATE_SHORT_REFS);
1161 format_decorations(sb, commit, c->auto_color);
1162 return 1;
1163 case 'D':
1164 load_ref_decorations(DECORATE_SHORT_REFS);
1165 format_decorations_extended(sb, commit, c->auto_color, "", ", ", "");
1166 return 1;
1167 case 'g': /* reflog info */
1168 switch(placeholder[1]) {
1169 case 'd': /* reflog selector */
1170 case 'D':
1171 if (c->pretty_ctx->reflog_info)
1172 get_reflog_selector(sb,
1173 c->pretty_ctx->reflog_info,
1174 &c->pretty_ctx->date_mode,
1175 c->pretty_ctx->date_mode_explicit,
1176 (placeholder[1] == 'd'));
1177 return 2;
1178 case 's': /* reflog message */
1179 if (c->pretty_ctx->reflog_info)
1180 get_reflog_message(sb, c->pretty_ctx->reflog_info);
1181 return 2;
1182 case 'n':
1183 case 'N':
1184 case 'e':
1185 case 'E':
1186 return format_reflog_person(sb,
1187 placeholder[1],
1188 c->pretty_ctx->reflog_info,
1189 &c->pretty_ctx->date_mode);
1191 return 0; /* unknown %g placeholder */
1192 case 'N':
1193 if (c->pretty_ctx->notes_message) {
1194 strbuf_addstr(sb, c->pretty_ctx->notes_message);
1195 return 1;
1197 return 0;
1200 if (placeholder[0] == 'G') {
1201 if (!c->signature_check.result)
1202 check_commit_signature(c->commit, &(c->signature_check));
1203 switch (placeholder[1]) {
1204 case 'G':
1205 if (c->signature_check.gpg_output)
1206 strbuf_addstr(sb, c->signature_check.gpg_output);
1207 break;
1208 case '?':
1209 switch (c->signature_check.result) {
1210 case 'G':
1211 case 'B':
1212 case 'E':
1213 case 'U':
1214 case 'N':
1215 case 'X':
1216 case 'Y':
1217 case 'R':
1218 strbuf_addch(sb, c->signature_check.result);
1220 break;
1221 case 'S':
1222 if (c->signature_check.signer)
1223 strbuf_addstr(sb, c->signature_check.signer);
1224 break;
1225 case 'K':
1226 if (c->signature_check.key)
1227 strbuf_addstr(sb, c->signature_check.key);
1228 break;
1229 default:
1230 return 0;
1232 return 2;
1236 /* For the rest we have to parse the commit header. */
1237 if (!c->commit_header_parsed)
1238 parse_commit_header(c);
1240 switch (placeholder[0]) {
1241 case 'a': /* author ... */
1242 return format_person_part(sb, placeholder[1],
1243 msg + c->author.off, c->author.len,
1244 &c->pretty_ctx->date_mode);
1245 case 'c': /* committer ... */
1246 return format_person_part(sb, placeholder[1],
1247 msg + c->committer.off, c->committer.len,
1248 &c->pretty_ctx->date_mode);
1249 case 'e': /* encoding */
1250 if (c->commit_encoding)
1251 strbuf_addstr(sb, c->commit_encoding);
1252 return 1;
1253 case 'B': /* raw body */
1254 /* message_off is always left at the initial newline */
1255 strbuf_addstr(sb, msg + c->message_off + 1);
1256 return 1;
1259 /* Now we need to parse the commit message. */
1260 if (!c->commit_message_parsed)
1261 parse_commit_message(c);
1263 switch (placeholder[0]) {
1264 case 's': /* subject */
1265 format_subject(sb, msg + c->subject_off, " ");
1266 return 1;
1267 case 'f': /* sanitized subject */
1268 format_sanitized_subject(sb, msg + c->subject_off);
1269 return 1;
1270 case 'b': /* body */
1271 strbuf_addstr(sb, msg + c->body_off);
1272 return 1;
1275 if (starts_with(placeholder, "(trailers)")) {
1276 format_trailers(sb, msg + c->subject_off);
1277 return strlen("(trailers)");
1280 return 0; /* unknown placeholder */
1283 static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */
1284 const char *placeholder,
1285 struct format_commit_context *c)
1287 struct strbuf local_sb = STRBUF_INIT;
1288 int total_consumed = 0, len, padding = c->padding;
1289 if (padding < 0) {
1290 const char *start = strrchr(sb->buf, '\n');
1291 int occupied;
1292 if (!start)
1293 start = sb->buf;
1294 occupied = utf8_strnwidth(start, -1, 1);
1295 occupied += c->pretty_ctx->graph_width;
1296 padding = (-padding) - occupied;
1298 while (1) {
1299 int modifier = *placeholder == 'C';
1300 int consumed = format_commit_one(&local_sb, placeholder, c);
1301 total_consumed += consumed;
1303 if (!modifier)
1304 break;
1306 placeholder += consumed;
1307 if (*placeholder != '%')
1308 break;
1309 placeholder++;
1310 total_consumed++;
1312 len = utf8_strnwidth(local_sb.buf, -1, 1);
1314 if (c->flush_type == flush_left_and_steal) {
1315 const char *ch = sb->buf + sb->len - 1;
1316 while (len > padding && ch > sb->buf) {
1317 const char *p;
1318 if (*ch == ' ') {
1319 ch--;
1320 padding++;
1321 continue;
1323 /* check for trailing ansi sequences */
1324 if (*ch != 'm')
1325 break;
1326 p = ch - 1;
1327 while (ch - p < 10 && *p != '\033')
1328 p--;
1329 if (*p != '\033' ||
1330 ch + 1 - p != display_mode_esc_sequence_len(p))
1331 break;
1333 * got a good ansi sequence, put it back to
1334 * local_sb as we're cutting sb
1336 strbuf_insert(&local_sb, 0, p, ch + 1 - p);
1337 ch = p - 1;
1339 strbuf_setlen(sb, ch + 1 - sb->buf);
1340 c->flush_type = flush_left;
1343 if (len > padding) {
1344 switch (c->truncate) {
1345 case trunc_left:
1346 strbuf_utf8_replace(&local_sb,
1347 0, len - (padding - 2),
1348 "..");
1349 break;
1350 case trunc_middle:
1351 strbuf_utf8_replace(&local_sb,
1352 padding / 2 - 1,
1353 len - (padding - 2),
1354 "..");
1355 break;
1356 case trunc_right:
1357 strbuf_utf8_replace(&local_sb,
1358 padding - 2, len - (padding - 2),
1359 "..");
1360 break;
1361 case trunc_none:
1362 break;
1364 strbuf_addbuf(sb, &local_sb);
1365 } else {
1366 int sb_len = sb->len, offset = 0;
1367 if (c->flush_type == flush_left)
1368 offset = padding - len;
1369 else if (c->flush_type == flush_both)
1370 offset = (padding - len) / 2;
1372 * we calculate padding in columns, now
1373 * convert it back to chars
1375 padding = padding - len + local_sb.len;
1376 strbuf_addchars(sb, ' ', padding);
1377 memcpy(sb->buf + sb_len + offset, local_sb.buf,
1378 local_sb.len);
1380 strbuf_release(&local_sb);
1381 c->flush_type = no_flush;
1382 return total_consumed;
1385 static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */
1386 const char *placeholder,
1387 void *context)
1389 int consumed;
1390 size_t orig_len;
1391 enum {
1392 NO_MAGIC,
1393 ADD_LF_BEFORE_NON_EMPTY,
1394 DEL_LF_BEFORE_EMPTY,
1395 ADD_SP_BEFORE_NON_EMPTY
1396 } magic = NO_MAGIC;
1398 switch (placeholder[0]) {
1399 case '-':
1400 magic = DEL_LF_BEFORE_EMPTY;
1401 break;
1402 case '+':
1403 magic = ADD_LF_BEFORE_NON_EMPTY;
1404 break;
1405 case ' ':
1406 magic = ADD_SP_BEFORE_NON_EMPTY;
1407 break;
1408 default:
1409 break;
1411 if (magic != NO_MAGIC)
1412 placeholder++;
1414 orig_len = sb->len;
1415 if (((struct format_commit_context *)context)->flush_type != no_flush)
1416 consumed = format_and_pad_commit(sb, placeholder, context);
1417 else
1418 consumed = format_commit_one(sb, placeholder, context);
1419 if (magic == NO_MAGIC)
1420 return consumed;
1422 if ((orig_len == sb->len) && magic == DEL_LF_BEFORE_EMPTY) {
1423 while (sb->len && sb->buf[sb->len - 1] == '\n')
1424 strbuf_setlen(sb, sb->len - 1);
1425 } else if (orig_len != sb->len) {
1426 if (magic == ADD_LF_BEFORE_NON_EMPTY)
1427 strbuf_insert(sb, orig_len, "\n", 1);
1428 else if (magic == ADD_SP_BEFORE_NON_EMPTY)
1429 strbuf_insert(sb, orig_len, " ", 1);
1431 return consumed + 1;
1434 static size_t userformat_want_item(struct strbuf *sb, const char *placeholder,
1435 void *context)
1437 struct userformat_want *w = context;
1439 if (*placeholder == '+' || *placeholder == '-' || *placeholder == ' ')
1440 placeholder++;
1442 switch (*placeholder) {
1443 case 'N':
1444 w->notes = 1;
1445 break;
1447 return 0;
1450 void userformat_find_requirements(const char *fmt, struct userformat_want *w)
1452 struct strbuf dummy = STRBUF_INIT;
1454 if (!fmt) {
1455 if (!user_format)
1456 return;
1457 fmt = user_format;
1459 strbuf_expand(&dummy, fmt, userformat_want_item, w);
1460 strbuf_release(&dummy);
1463 void format_commit_message(const struct commit *commit,
1464 const char *format, struct strbuf *sb,
1465 const struct pretty_print_context *pretty_ctx)
1467 struct format_commit_context context;
1468 const char *output_enc = pretty_ctx->output_encoding;
1469 const char *utf8 = "UTF-8";
1471 memset(&context, 0, sizeof(context));
1472 context.commit = commit;
1473 context.pretty_ctx = pretty_ctx;
1474 context.wrap_start = sb->len;
1476 * convert a commit message to UTF-8 first
1477 * as far as 'format_commit_item' assumes it in UTF-8
1479 context.message = logmsg_reencode(commit,
1480 &context.commit_encoding,
1481 utf8);
1483 strbuf_expand(sb, format, format_commit_item, &context);
1484 rewrap_message_tail(sb, &context, 0, 0, 0);
1486 /* then convert a commit message to an actual output encoding */
1487 if (output_enc) {
1488 if (same_encoding(utf8, output_enc))
1489 output_enc = NULL;
1490 } else {
1491 if (context.commit_encoding &&
1492 !same_encoding(context.commit_encoding, utf8))
1493 output_enc = context.commit_encoding;
1496 if (output_enc) {
1497 int outsz;
1498 char *out = reencode_string_len(sb->buf, sb->len,
1499 output_enc, utf8, &outsz);
1500 if (out)
1501 strbuf_attach(sb, out, outsz, outsz + 1);
1504 free(context.commit_encoding);
1505 unuse_commit_buffer(commit, context.message);
1508 static void pp_header(struct pretty_print_context *pp,
1509 const char *encoding,
1510 const struct commit *commit,
1511 const char **msg_p,
1512 struct strbuf *sb)
1514 int parents_shown = 0;
1516 for (;;) {
1517 const char *name, *line = *msg_p;
1518 int linelen = get_one_line(*msg_p);
1520 if (!linelen)
1521 return;
1522 *msg_p += linelen;
1524 if (linelen == 1)
1525 /* End of header */
1526 return;
1528 if (pp->fmt == CMIT_FMT_RAW) {
1529 strbuf_add(sb, line, linelen);
1530 continue;
1533 if (starts_with(line, "parent ")) {
1534 if (linelen != 48)
1535 die("bad parent line in commit");
1536 continue;
1539 if (!parents_shown) {
1540 unsigned num = commit_list_count(commit->parents);
1541 /* with enough slop */
1542 strbuf_grow(sb, num * 50 + 20);
1543 add_merge_info(pp, sb, commit);
1544 parents_shown = 1;
1548 * MEDIUM == DEFAULT shows only author with dates.
1549 * FULL shows both authors but not dates.
1550 * FULLER shows both authors and dates.
1552 if (skip_prefix(line, "author ", &name)) {
1553 strbuf_grow(sb, linelen + 80);
1554 pp_user_info(pp, "Author", sb, name, encoding);
1556 if (skip_prefix(line, "committer ", &name) &&
1557 (pp->fmt == CMIT_FMT_FULL || pp->fmt == CMIT_FMT_FULLER)) {
1558 strbuf_grow(sb, linelen + 80);
1559 pp_user_info(pp, "Commit", sb, name, encoding);
1564 void pp_title_line(struct pretty_print_context *pp,
1565 const char **msg_p,
1566 struct strbuf *sb,
1567 const char *encoding,
1568 int need_8bit_cte)
1570 static const int max_length = 78; /* per rfc2047 */
1571 struct strbuf title;
1573 strbuf_init(&title, 80);
1574 *msg_p = format_subject(&title, *msg_p,
1575 pp->preserve_subject ? "\n" : " ");
1577 strbuf_grow(sb, title.len + 1024);
1578 if (pp->print_email_subject) {
1579 if (pp->rev)
1580 fmt_output_email_subject(sb, pp->rev);
1581 if (needs_rfc2047_encoding(title.buf, title.len, RFC2047_SUBJECT))
1582 add_rfc2047(sb, title.buf, title.len,
1583 encoding, RFC2047_SUBJECT);
1584 else
1585 strbuf_add_wrapped_bytes(sb, title.buf, title.len,
1586 -last_line_length(sb), 1, max_length);
1587 } else {
1588 strbuf_addbuf(sb, &title);
1590 strbuf_addch(sb, '\n');
1592 if (need_8bit_cte == 0) {
1593 int i;
1594 for (i = 0; i < pp->in_body_headers.nr; i++) {
1595 if (has_non_ascii(pp->in_body_headers.items[i].string)) {
1596 need_8bit_cte = 1;
1597 break;
1602 if (need_8bit_cte > 0) {
1603 const char *header_fmt =
1604 "MIME-Version: 1.0\n"
1605 "Content-Type: text/plain; charset=%s\n"
1606 "Content-Transfer-Encoding: 8bit\n";
1607 strbuf_addf(sb, header_fmt, encoding);
1609 if (pp->after_subject) {
1610 strbuf_addstr(sb, pp->after_subject);
1612 if (cmit_fmt_is_mail(pp->fmt)) {
1613 strbuf_addch(sb, '\n');
1616 if (pp->in_body_headers.nr) {
1617 int i;
1618 for (i = 0; i < pp->in_body_headers.nr; i++) {
1619 strbuf_addstr(sb, pp->in_body_headers.items[i].string);
1620 free(pp->in_body_headers.items[i].string);
1622 string_list_clear(&pp->in_body_headers, 0);
1623 strbuf_addch(sb, '\n');
1626 strbuf_release(&title);
1629 static int pp_utf8_width(const char *start, const char *end)
1631 int width = 0;
1632 size_t remain = end - start;
1634 while (remain) {
1635 int n = utf8_width(&start, &remain);
1636 if (n < 0 || !start)
1637 return -1;
1638 width += n;
1640 return width;
1643 static void strbuf_add_tabexpand(struct strbuf *sb, int tabwidth,
1644 const char *line, int linelen)
1646 const char *tab;
1648 while ((tab = memchr(line, '\t', linelen)) != NULL) {
1649 int width = pp_utf8_width(line, tab);
1652 * If it wasn't well-formed utf8, or it
1653 * had characters with badly defined
1654 * width (control characters etc), just
1655 * give up on trying to align things.
1657 if (width < 0)
1658 break;
1660 /* Output the data .. */
1661 strbuf_add(sb, line, tab - line);
1663 /* .. and the de-tabified tab */
1664 strbuf_addchars(sb, ' ', tabwidth - (width % tabwidth));
1666 /* Skip over the printed part .. */
1667 linelen -= tab + 1 - line;
1668 line = tab + 1;
1672 * Print out everything after the last tab without
1673 * worrying about width - there's nothing more to
1674 * align.
1676 strbuf_add(sb, line, linelen);
1680 * pp_handle_indent() prints out the intendation, and
1681 * the whole line (without the final newline), after
1682 * de-tabifying.
1684 static void pp_handle_indent(struct pretty_print_context *pp,
1685 struct strbuf *sb, int indent,
1686 const char *line, int linelen)
1688 strbuf_addchars(sb, ' ', indent);
1689 if (pp->expand_tabs_in_log)
1690 strbuf_add_tabexpand(sb, pp->expand_tabs_in_log, line, linelen);
1691 else
1692 strbuf_add(sb, line, linelen);
1695 static int is_mboxrd_from(const char *line, int len)
1698 * a line matching /^From $/ here would only have len == 4
1699 * at this point because is_empty_line would've trimmed all
1700 * trailing space
1702 return len > 4 && starts_with(line + strspn(line, ">"), "From ");
1705 void pp_remainder(struct pretty_print_context *pp,
1706 const char **msg_p,
1707 struct strbuf *sb,
1708 int indent)
1710 int first = 1;
1711 for (;;) {
1712 const char *line = *msg_p;
1713 int linelen = get_one_line(line);
1714 *msg_p += linelen;
1716 if (!linelen)
1717 break;
1719 if (is_blank_line(line, &linelen)) {
1720 if (first)
1721 continue;
1722 if (pp->fmt == CMIT_FMT_SHORT)
1723 break;
1725 first = 0;
1727 strbuf_grow(sb, linelen + indent + 20);
1728 if (indent)
1729 pp_handle_indent(pp, sb, indent, line, linelen);
1730 else if (pp->expand_tabs_in_log)
1731 strbuf_add_tabexpand(sb, pp->expand_tabs_in_log,
1732 line, linelen);
1733 else {
1734 if (pp->fmt == CMIT_FMT_MBOXRD &&
1735 is_mboxrd_from(line, linelen))
1736 strbuf_addch(sb, '>');
1738 strbuf_add(sb, line, linelen);
1740 strbuf_addch(sb, '\n');
1744 void pretty_print_commit(struct pretty_print_context *pp,
1745 const struct commit *commit,
1746 struct strbuf *sb)
1748 unsigned long beginning_of_body;
1749 int indent = 4;
1750 const char *msg;
1751 const char *reencoded;
1752 const char *encoding;
1753 int need_8bit_cte = pp->need_8bit_cte;
1755 if (pp->fmt == CMIT_FMT_USERFORMAT) {
1756 format_commit_message(commit, user_format, sb, pp);
1757 return;
1760 encoding = get_log_output_encoding();
1761 msg = reencoded = logmsg_reencode(commit, NULL, encoding);
1763 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
1764 indent = 0;
1767 * We need to check and emit Content-type: to mark it
1768 * as 8-bit if we haven't done so.
1770 if (cmit_fmt_is_mail(pp->fmt) && need_8bit_cte == 0) {
1771 int i, ch, in_body;
1773 for (in_body = i = 0; (ch = msg[i]); i++) {
1774 if (!in_body) {
1775 /* author could be non 7-bit ASCII but
1776 * the log may be so; skip over the
1777 * header part first.
1779 if (ch == '\n' && msg[i+1] == '\n')
1780 in_body = 1;
1782 else if (non_ascii(ch)) {
1783 need_8bit_cte = 1;
1784 break;
1789 pp_header(pp, encoding, commit, &msg, sb);
1790 if (pp->fmt != CMIT_FMT_ONELINE && !pp->print_email_subject) {
1791 strbuf_addch(sb, '\n');
1794 /* Skip excess blank lines at the beginning of body, if any... */
1795 msg = skip_blank_lines(msg);
1797 /* These formats treat the title line specially. */
1798 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
1799 pp_title_line(pp, &msg, sb, encoding, need_8bit_cte);
1801 beginning_of_body = sb->len;
1802 if (pp->fmt != CMIT_FMT_ONELINE)
1803 pp_remainder(pp, &msg, sb, indent);
1804 strbuf_rtrim(sb);
1806 /* Make sure there is an EOLN for the non-oneline case */
1807 if (pp->fmt != CMIT_FMT_ONELINE)
1808 strbuf_addch(sb, '\n');
1811 * The caller may append additional body text in e-mail
1812 * format. Make sure we did not strip the blank line
1813 * between the header and the body.
1815 if (cmit_fmt_is_mail(pp->fmt) && sb->len <= beginning_of_body)
1816 strbuf_addch(sb, '\n');
1818 unuse_commit_buffer(commit, reencoded);
1821 void pp_commit_easy(enum cmit_fmt fmt, const struct commit *commit,
1822 struct strbuf *sb)
1824 struct pretty_print_context pp = {0};
1825 pp.fmt = fmt;
1826 pretty_print_commit(&pp, commit, sb);