]> git.ipfire.org Git - thirdparty/git.git/blob - pretty.c
aae6e792bc43097a72f9a62ed6b1a1cd852157e5
[thirdparty/git.git] / pretty.c
1 #include "cache.h"
2 #include "config.h"
3 #include "commit.h"
4 #include "utf8.h"
5 #include "diff.h"
6 #include "revision.h"
7 #include "string-list.h"
8 #include "mailmap.h"
9 #include "log-tree.h"
10 #include "notes.h"
11 #include "color.h"
12 #include "reflog-walk.h"
13 #include "gpg-interface.h"
14 #include "trailer.h"
15
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);
30
31 int commit_format_is_empty(enum cmit_fmt fmt)
32 {
33 return fmt == CMIT_FMT_USERFORMAT && !*user_format;
34 }
35
36 static void save_user_format(struct rev_info *rev, const char *cp, int is_tformat)
37 {
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;
43 }
44
45 static int git_pretty_formats_config(const char *var, const char *value, void *cb)
46 {
47 struct cmt_fmt_map *commit_format = NULL;
48 const char *name;
49 const char *fmt;
50 int i;
51
52 if (!skip_prefix(var, "pretty.", &name))
53 return 0;
54
55 for (i = 0; i < builtin_formats_len; i++) {
56 if (!strcmp(commit_formats[i].name, name))
57 return 0;
58 }
59
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;
64 }
65 }
66
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++;
73 }
74
75 commit_format->name = xstrdup(name);
76 commit_format->format = CMIT_FMT_USERFORMAT;
77 if (git_config_string(&fmt, var, value))
78 return -1;
79
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;
87
88 return 0;
89 }
90
91 static void setup_commit_formats(void)
92 {
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)" },
104 /*
105 * Please update $__git_log_pretty_formats in
106 * git-completion.bash when you add new formats.
107 */
108 };
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));
114
115 git_config(git_pretty_formats_config, NULL);
116 }
117
118 static struct cmt_fmt_map *find_commit_format_recursive(const char *sought,
119 const char *original,
120 int num_redirections)
121 {
122 struct cmt_fmt_map *found = NULL;
123 size_t found_match_len = 0;
124 int i;
125
126 if (num_redirections >= commit_formats_len)
127 die("invalid --pretty format: "
128 "'%s' references an alias which points to itself",
129 original);
130
131 for (i = 0; i < commit_formats_len; i++) {
132 size_t match_len;
133
134 if (!starts_with(commit_formats[i].name, sought))
135 continue;
136
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;
141 }
142 }
143
144 if (found && found->is_alias) {
145 found = find_commit_format_recursive(found->user_format,
146 original,
147 num_redirections+1);
148 }
149
150 return found;
151 }
152
153 static struct cmt_fmt_map *find_commit_format(const char *sought)
154 {
155 if (!commit_formats)
156 setup_commit_formats();
157
158 return find_commit_format_recursive(sought, sought, 0);
159 }
160
161 void get_commit_format(const char *arg, struct rev_info *rev)
162 {
163 struct cmt_fmt_map *commit_format;
164
165 rev->use_terminator = 0;
166 if (!arg) {
167 rev->commit_format = CMIT_FMT_DEFAULT;
168 return;
169 }
170 if (skip_prefix(arg, "format:", &arg)) {
171 save_user_format(rev, arg, 0);
172 return;
173 }
174
175 if (!*arg || skip_prefix(arg, "tformat:", &arg) || strchr(arg, '%')) {
176 save_user_format(rev, arg, 1);
177 return;
178 }
179
180 commit_format = find_commit_format(arg);
181 if (!commit_format)
182 die("invalid --pretty format: %s", arg);
183
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);
192 }
193 }
194
195 /*
196 * Generic support for pretty-printing the header
197 */
198 static int get_one_line(const char *msg)
199 {
200 int ret = 0;
201
202 for (;;) {
203 char c = *msg++;
204 if (!c)
205 break;
206 ret++;
207 if (c == '\n')
208 break;
209 }
210 return ret;
211 }
212
213 /* High bit set, or ISO-2022-INT */
214 static int non_ascii(int ch)
215 {
216 return !isascii(ch) || ch == '\033';
217 }
218
219 int has_non_ascii(const char *s)
220 {
221 int ch;
222 if (!s)
223 return 0;
224 while ((ch = *s++) != '\0') {
225 if (non_ascii(ch))
226 return 1;
227 }
228 return 0;
229 }
230
231 static int is_rfc822_special(char ch)
232 {
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;
250 }
251 }
252
253 static int needs_rfc822_quoting(const char *s, int len)
254 {
255 int i;
256 for (i = 0; i < len; i++)
257 if (is_rfc822_special(s[i]))
258 return 1;
259 return 0;
260 }
261
262 static int last_line_length(struct strbuf *sb)
263 {
264 int i;
265
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);
271 }
272
273 static void add_rfc822_quoted(struct strbuf *out, const char *s, int len)
274 {
275 int i;
276
277 /* just a guess, we may have to also backslash-quote */
278 strbuf_grow(out, len + 2);
279
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]);
289 }
290 }
291 strbuf_addch(out, '"');
292 }
293
294 enum rfc2047_type {
295 RFC2047_SUBJECT,
296 RFC2047_ADDRESS
297 };
298
299 static int is_rfc2047_special(char ch, enum rfc2047_type type)
300 {
301 /*
302 * rfc2047, section 4.2:
303 *
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.
309 */
310
311 /*
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)
315 */
316 if (non_ascii(ch) || !isprint(ch))
317 return 1;
318
319 /*
320 * rule out special printable characters (' ' should be the only
321 * whitespace character considered printable, but be defensive and use
322 * isspace())
323 */
324 if (isspace(ch) || ch == '=' || ch == '?' || ch == '_')
325 return 1;
326
327 /*
328 * rfc2047, section 5.3:
329 *
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:
333 *
334 * phrase = 1*( encoded-word / word )
335 *
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'.
342 */
343
344 if (type != RFC2047_ADDRESS)
345 return 0;
346
347 /* '=' and '_' are special cases and have been checked above */
348 return !(isalnum(ch) || ch == '!' || ch == '*' || ch == '+' || ch == '-' || ch == '/');
349 }
350
351 static int needs_rfc2047_encoding(const char *line, int len)
352 {
353 int i;
354
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;
361 }
362
363 return 0;
364 }
365
366 static void add_rfc2047(struct strbuf *sb, const char *line, size_t len,
367 const char *encoding, enum rfc2047_type type)
368 {
369 static const int max_encoded_length = 76; /* per rfc2047 */
370 int i;
371 int line_len = last_line_length(sb);
372
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? */
376
377 while (len) {
378 /*
379 * RFC 2047, section 5 (3):
380 *
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.
384 */
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);
388
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;
392
393 /*
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.
399 */
400
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 */
405 }
406
407 for (i = 0; i < chrlen; i++)
408 strbuf_addf(sb, encoded_fmt, p[i]);
409 line_len += encoded_len;
410 }
411 strbuf_addstr(sb, "?=");
412 }
413
414 const char *show_ident_date(const struct ident_split *ident,
415 const struct date_mode *mode)
416 {
417 timestamp_t date = 0;
418 long tz = 0;
419
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;
429 }
430 return show_date(date, tz, mode);
431 }
432
433 void pp_user_info(struct pretty_print_context *pp,
434 const char *what, struct strbuf *sb,
435 const char *line, const char *encoding)
436 {
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 */
442
443 if (pp->fmt == CMIT_FMT_ONELINE)
444 return;
445
446 line_end = strchrnul(line, '\n');
447 if (split_ident_line(&ident, line, line_end - line))
448 return;
449
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;
454
455 if (pp->mailmap)
456 map_user(pp->mailmap, &mailbuf, &maillen, &namebuf, &namelen);
457
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;
461
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));
469
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;
474 }
475
476 strbuf_addstr(sb, "From: ");
477 if (pp->encode_email_headers &&
478 needs_rfc2047_encoding(namebuf, namelen)) {
479 add_rfc2047(sb, namebuf, namelen,
480 encoding, RFC2047_ADDRESS);
481 max_length = 76; /* per rfc2047 */
482 } else if (needs_rfc822_quoting(namebuf, namelen)) {
483 struct strbuf quoted = STRBUF_INIT;
484 add_rfc822_quoted(&quoted, namebuf, namelen);
485 strbuf_add_wrapped_bytes(sb, quoted.buf, quoted.len,
486 -6, 1, max_length);
487 strbuf_release(&quoted);
488 } else {
489 strbuf_add_wrapped_bytes(sb, namebuf, namelen,
490 -6, 1, max_length);
491 }
492
493 if (max_length <
494 last_line_length(sb) + strlen(" <") + maillen + strlen(">"))
495 strbuf_addch(sb, '\n');
496 strbuf_addf(sb, " <%.*s>\n", (int)maillen, mailbuf);
497 } else {
498 strbuf_addf(sb, "%s: %.*s%.*s <%.*s>\n", what,
499 (pp->fmt == CMIT_FMT_FULLER) ? 4 : 0, " ",
500 (int)namelen, namebuf, (int)maillen, mailbuf);
501 }
502
503 switch (pp->fmt) {
504 case CMIT_FMT_MEDIUM:
505 strbuf_addf(sb, "Date: %s\n",
506 show_ident_date(&ident, &pp->date_mode));
507 break;
508 case CMIT_FMT_EMAIL:
509 case CMIT_FMT_MBOXRD:
510 strbuf_addf(sb, "Date: %s\n",
511 show_ident_date(&ident, DATE_MODE(RFC2822)));
512 break;
513 case CMIT_FMT_FULLER:
514 strbuf_addf(sb, "%sDate: %s\n", what,
515 show_ident_date(&ident, &pp->date_mode));
516 break;
517 default:
518 /* notin' */
519 break;
520 }
521 }
522
523 static int is_blank_line(const char *line, int *len_p)
524 {
525 int len = *len_p;
526 while (len && isspace(line[len - 1]))
527 len--;
528 *len_p = len;
529 return !len;
530 }
531
532 const char *skip_blank_lines(const char *msg)
533 {
534 for (;;) {
535 int linelen = get_one_line(msg);
536 int ll = linelen;
537 if (!linelen)
538 break;
539 if (!is_blank_line(msg, &ll))
540 break;
541 msg += linelen;
542 }
543 return msg;
544 }
545
546 static void add_merge_info(const struct pretty_print_context *pp,
547 struct strbuf *sb, const struct commit *commit)
548 {
549 struct commit_list *parent = commit->parents;
550
551 if ((pp->fmt == CMIT_FMT_ONELINE) || (cmit_fmt_is_mail(pp->fmt)) ||
552 !parent || !parent->next)
553 return;
554
555 strbuf_addstr(sb, "Merge:");
556
557 while (parent) {
558 struct object_id *oidp = &parent->item->object.oid;
559 strbuf_addch(sb, ' ');
560 if (pp->abbrev)
561 strbuf_add_unique_abbrev(sb, oidp, pp->abbrev);
562 else
563 strbuf_addstr(sb, oid_to_hex(oidp));
564 parent = parent->next;
565 }
566 strbuf_addch(sb, '\n');
567 }
568
569 static char *get_header(const char *msg, const char *key)
570 {
571 size_t len;
572 const char *v = find_commit_header(msg, key, &len);
573 return v ? xmemdupz(v, len) : NULL;
574 }
575
576 static char *replace_encoding_header(char *buf, const char *encoding)
577 {
578 struct strbuf tmp = STRBUF_INIT;
579 size_t start, len;
580 char *cp = buf;
581
582 /* guess if there is an encoding header before a \n\n */
583 while (!starts_with(cp, "encoding ")) {
584 cp = strchr(cp, '\n');
585 if (!cp || *++cp == '\n')
586 return buf;
587 }
588 start = cp - buf;
589 cp = strchr(cp, '\n');
590 if (!cp)
591 return buf; /* should not happen but be defensive */
592 len = cp + 1 - (buf + start);
593
594 strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
595 if (is_encoding_utf8(encoding)) {
596 /* we have re-coded to UTF-8; drop the header */
597 strbuf_remove(&tmp, start, len);
598 } else {
599 /* just replaces XXXX in 'encoding XXXX\n' */
600 strbuf_splice(&tmp, start + strlen("encoding "),
601 len - strlen("encoding \n"),
602 encoding, strlen(encoding));
603 }
604 return strbuf_detach(&tmp, NULL);
605 }
606
607 const char *repo_logmsg_reencode(struct repository *r,
608 const struct commit *commit,
609 char **commit_encoding,
610 const char *output_encoding)
611 {
612 static const char *utf8 = "UTF-8";
613 const char *use_encoding;
614 char *encoding;
615 const char *msg = repo_get_commit_buffer(r, commit, NULL);
616 char *out;
617
618 if (!output_encoding || !*output_encoding) {
619 if (commit_encoding)
620 *commit_encoding = get_header(msg, "encoding");
621 return msg;
622 }
623 encoding = get_header(msg, "encoding");
624 if (commit_encoding)
625 *commit_encoding = encoding;
626 use_encoding = encoding ? encoding : utf8;
627 if (same_encoding(use_encoding, output_encoding)) {
628 /*
629 * No encoding work to be done. If we have no encoding header
630 * at all, then there's nothing to do, and we can return the
631 * message verbatim (whether newly allocated or not).
632 */
633 if (!encoding)
634 return msg;
635
636 /*
637 * Otherwise, we still want to munge the encoding header in the
638 * result, which will be done by modifying the buffer. If we
639 * are using a fresh copy, we can reuse it. But if we are using
640 * the cached copy from get_commit_buffer, we need to duplicate it
641 * to avoid munging the cached copy.
642 */
643 if (msg == get_cached_commit_buffer(r, commit, NULL))
644 out = xstrdup(msg);
645 else
646 out = (char *)msg;
647 }
648 else {
649 /*
650 * There's actual encoding work to do. Do the reencoding, which
651 * still leaves the header to be replaced in the next step. At
652 * this point, we are done with msg. If we allocated a fresh
653 * copy, we can free it.
654 */
655 out = reencode_string(msg, output_encoding, use_encoding);
656 if (out)
657 repo_unuse_commit_buffer(r, commit, msg);
658 }
659
660 /*
661 * This replacement actually consumes the buffer we hand it, so we do
662 * not have to worry about freeing the old "out" here.
663 */
664 if (out)
665 out = replace_encoding_header(out, output_encoding);
666
667 if (!commit_encoding)
668 free(encoding);
669 /*
670 * If the re-encoding failed, out might be NULL here; in that
671 * case we just return the commit message verbatim.
672 */
673 return out ? out : msg;
674 }
675
676 static int mailmap_name(const char **email, size_t *email_len,
677 const char **name, size_t *name_len)
678 {
679 static struct string_list *mail_map;
680 if (!mail_map) {
681 mail_map = xcalloc(1, sizeof(*mail_map));
682 read_mailmap(mail_map, NULL);
683 }
684 return mail_map->nr && map_user(mail_map, email, email_len, name, name_len);
685 }
686
687 static size_t format_person_part(struct strbuf *sb, char part,
688 const char *msg, int len,
689 const struct date_mode *dmode)
690 {
691 /* currently all placeholders have same length */
692 const int placeholder_len = 2;
693 struct ident_split s;
694 const char *name, *mail;
695 size_t maillen, namelen;
696
697 if (split_ident_line(&s, msg, len) < 0)
698 goto skip;
699
700 name = s.name_begin;
701 namelen = s.name_end - s.name_begin;
702 mail = s.mail_begin;
703 maillen = s.mail_end - s.mail_begin;
704
705 if (part == 'N' || part == 'E' || part == 'L') /* mailmap lookup */
706 mailmap_name(&mail, &maillen, &name, &namelen);
707 if (part == 'n' || part == 'N') { /* name */
708 strbuf_add(sb, name, namelen);
709 return placeholder_len;
710 }
711 if (part == 'e' || part == 'E') { /* email */
712 strbuf_add(sb, mail, maillen);
713 return placeholder_len;
714 }
715 if (part == 'l' || part == 'L') { /* local-part */
716 const char *at = memchr(mail, '@', maillen);
717 if (at)
718 maillen = at - mail;
719 strbuf_add(sb, mail, maillen);
720 return placeholder_len;
721 }
722
723 if (!s.date_begin)
724 goto skip;
725
726 if (part == 't') { /* date, UNIX timestamp */
727 strbuf_add(sb, s.date_begin, s.date_end - s.date_begin);
728 return placeholder_len;
729 }
730
731 switch (part) {
732 case 'd': /* date */
733 strbuf_addstr(sb, show_ident_date(&s, dmode));
734 return placeholder_len;
735 case 'D': /* date, RFC2822 style */
736 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RFC2822)));
737 return placeholder_len;
738 case 'r': /* date, relative */
739 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RELATIVE)));
740 return placeholder_len;
741 case 'i': /* date, ISO 8601-like */
742 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601)));
743 return placeholder_len;
744 case 'I': /* date, ISO 8601 strict */
745 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601_STRICT)));
746 return placeholder_len;
747 case 's':
748 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(SHORT)));
749 return placeholder_len;
750 }
751
752 skip:
753 /*
754 * reading from either a bogus commit, or a reflog entry with
755 * %gn, %ge, etc.; 'sb' cannot be updated, but we still need
756 * to compute a valid return value.
757 */
758 if (part == 'n' || part == 'e' || part == 't' || part == 'd'
759 || part == 'D' || part == 'r' || part == 'i')
760 return placeholder_len;
761
762 return 0; /* unknown placeholder */
763 }
764
765 struct chunk {
766 size_t off;
767 size_t len;
768 };
769
770 enum flush_type {
771 no_flush,
772 flush_right,
773 flush_left,
774 flush_left_and_steal,
775 flush_both
776 };
777
778 enum trunc_type {
779 trunc_none,
780 trunc_left,
781 trunc_middle,
782 trunc_right
783 };
784
785 struct format_commit_context {
786 const struct commit *commit;
787 const struct pretty_print_context *pretty_ctx;
788 unsigned commit_header_parsed:1;
789 unsigned commit_message_parsed:1;
790 struct signature_check signature_check;
791 enum flush_type flush_type;
792 enum trunc_type truncate;
793 const char *message;
794 char *commit_encoding;
795 size_t width, indent1, indent2;
796 int auto_color;
797 int padding;
798
799 /* These offsets are relative to the start of the commit message. */
800 struct chunk author;
801 struct chunk committer;
802 size_t message_off;
803 size_t subject_off;
804 size_t body_off;
805
806 /* The following ones are relative to the result struct strbuf. */
807 size_t wrap_start;
808 };
809
810 static void parse_commit_header(struct format_commit_context *context)
811 {
812 const char *msg = context->message;
813 int i;
814
815 for (i = 0; msg[i]; i++) {
816 const char *name;
817 int eol;
818 for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
819 ; /* do nothing */
820
821 if (i == eol) {
822 break;
823 } else if (skip_prefix(msg + i, "author ", &name)) {
824 context->author.off = name - msg;
825 context->author.len = msg + eol - name;
826 } else if (skip_prefix(msg + i, "committer ", &name)) {
827 context->committer.off = name - msg;
828 context->committer.len = msg + eol - name;
829 }
830 i = eol;
831 }
832 context->message_off = i;
833 context->commit_header_parsed = 1;
834 }
835
836 static int istitlechar(char c)
837 {
838 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
839 (c >= '0' && c <= '9') || c == '.' || c == '_';
840 }
841
842 void format_sanitized_subject(struct strbuf *sb, const char *msg, size_t len)
843 {
844 size_t trimlen;
845 size_t start_len = sb->len;
846 int space = 2;
847 int i;
848
849 for (i = 0; i < len; i++) {
850 if (istitlechar(msg[i])) {
851 if (space == 1)
852 strbuf_addch(sb, '-');
853 space = 0;
854 strbuf_addch(sb, msg[i]);
855 if (msg[i] == '.')
856 while (msg[i+1] == '.')
857 i++;
858 } else
859 space |= 1;
860 }
861
862 /* trim any trailing '.' or '-' characters */
863 trimlen = 0;
864 while (sb->len - trimlen > start_len &&
865 (sb->buf[sb->len - 1 - trimlen] == '.'
866 || sb->buf[sb->len - 1 - trimlen] == '-'))
867 trimlen++;
868 strbuf_remove(sb, sb->len - trimlen, trimlen);
869 }
870
871 const char *format_subject(struct strbuf *sb, const char *msg,
872 const char *line_separator)
873 {
874 int first = 1;
875
876 for (;;) {
877 const char *line = msg;
878 int linelen = get_one_line(line);
879
880 msg += linelen;
881 if (!linelen || is_blank_line(line, &linelen))
882 break;
883
884 if (!sb)
885 continue;
886 strbuf_grow(sb, linelen + 2);
887 if (!first)
888 strbuf_addstr(sb, line_separator);
889 strbuf_add(sb, line, linelen);
890 first = 0;
891 }
892 return msg;
893 }
894
895 static void parse_commit_message(struct format_commit_context *c)
896 {
897 const char *msg = c->message + c->message_off;
898 const char *start = c->message;
899
900 msg = skip_blank_lines(msg);
901 c->subject_off = msg - start;
902
903 msg = format_subject(NULL, msg, NULL);
904 msg = skip_blank_lines(msg);
905 c->body_off = msg - start;
906
907 c->commit_message_parsed = 1;
908 }
909
910 static void strbuf_wrap(struct strbuf *sb, size_t pos,
911 size_t width, size_t indent1, size_t indent2)
912 {
913 struct strbuf tmp = STRBUF_INIT;
914
915 if (pos)
916 strbuf_add(&tmp, sb->buf, pos);
917 strbuf_add_wrapped_text(&tmp, sb->buf + pos,
918 cast_size_t_to_int(indent1),
919 cast_size_t_to_int(indent2),
920 cast_size_t_to_int(width));
921 strbuf_swap(&tmp, sb);
922 strbuf_release(&tmp);
923 }
924
925 static void rewrap_message_tail(struct strbuf *sb,
926 struct format_commit_context *c,
927 size_t new_width, size_t new_indent1,
928 size_t new_indent2)
929 {
930 if (c->width == new_width && c->indent1 == new_indent1 &&
931 c->indent2 == new_indent2)
932 return;
933 if (c->wrap_start < sb->len)
934 strbuf_wrap(sb, c->wrap_start, c->width, c->indent1, c->indent2);
935 c->wrap_start = sb->len;
936 c->width = new_width;
937 c->indent1 = new_indent1;
938 c->indent2 = new_indent2;
939 }
940
941 static int format_reflog_person(struct strbuf *sb,
942 char part,
943 struct reflog_walk_info *log,
944 const struct date_mode *dmode)
945 {
946 const char *ident;
947
948 if (!log)
949 return 2;
950
951 ident = get_reflog_ident(log);
952 if (!ident)
953 return 2;
954
955 return format_person_part(sb, part, ident, strlen(ident), dmode);
956 }
957
958 static size_t parse_color(struct strbuf *sb, /* in UTF-8 */
959 const char *placeholder,
960 struct format_commit_context *c)
961 {
962 const char *rest = placeholder;
963 const char *basic_color = NULL;
964
965 if (placeholder[1] == '(') {
966 const char *begin = placeholder + 2;
967 const char *end = strchr(begin, ')');
968 char color[COLOR_MAXLEN];
969
970 if (!end)
971 return 0;
972
973 if (skip_prefix(begin, "auto,", &begin)) {
974 if (!want_color(c->pretty_ctx->color))
975 return end - placeholder + 1;
976 } else if (skip_prefix(begin, "always,", &begin)) {
977 /* nothing to do; we do not respect want_color at all */
978 } else {
979 /* the default is the same as "auto" */
980 if (!want_color(c->pretty_ctx->color))
981 return end - placeholder + 1;
982 }
983
984 if (color_parse_mem(begin, end - begin, color) < 0)
985 die(_("unable to parse --pretty format"));
986 strbuf_addstr(sb, color);
987 return end - placeholder + 1;
988 }
989
990 /*
991 * We handle things like "%C(red)" above; for historical reasons, there
992 * are a few colors that can be specified without parentheses (and
993 * they cannot support things like "auto" or "always" at all).
994 */
995 if (skip_prefix(placeholder + 1, "red", &rest))
996 basic_color = GIT_COLOR_RED;
997 else if (skip_prefix(placeholder + 1, "green", &rest))
998 basic_color = GIT_COLOR_GREEN;
999 else if (skip_prefix(placeholder + 1, "blue", &rest))
1000 basic_color = GIT_COLOR_BLUE;
1001 else if (skip_prefix(placeholder + 1, "reset", &rest))
1002 basic_color = GIT_COLOR_RESET;
1003
1004 if (basic_color && want_color(c->pretty_ctx->color))
1005 strbuf_addstr(sb, basic_color);
1006
1007 return rest - placeholder;
1008 }
1009
1010 static size_t parse_padding_placeholder(const char *placeholder,
1011 struct format_commit_context *c)
1012 {
1013 const char *ch = placeholder;
1014 enum flush_type flush_type;
1015 int to_column = 0;
1016
1017 switch (*ch++) {
1018 case '<':
1019 flush_type = flush_right;
1020 break;
1021 case '>':
1022 if (*ch == '<') {
1023 flush_type = flush_both;
1024 ch++;
1025 } else if (*ch == '>') {
1026 flush_type = flush_left_and_steal;
1027 ch++;
1028 } else
1029 flush_type = flush_left;
1030 break;
1031 default:
1032 return 0;
1033 }
1034
1035 /* the next value means "wide enough to that column" */
1036 if (*ch == '|') {
1037 to_column = 1;
1038 ch++;
1039 }
1040
1041 if (*ch == '(') {
1042 const char *start = ch + 1;
1043 const char *end = start + strcspn(start, ",)");
1044 char *next;
1045 int width;
1046 if (!*end || end == start)
1047 return 0;
1048 width = strtol(start, &next, 10);
1049 if (next == start || width == 0)
1050 return 0;
1051 if (width < 0) {
1052 if (to_column)
1053 width += term_columns();
1054 if (width < 0)
1055 return 0;
1056 }
1057 c->padding = to_column ? -width : width;
1058 c->flush_type = flush_type;
1059
1060 if (*end == ',') {
1061 start = end + 1;
1062 end = strchr(start, ')');
1063 if (!end || end == start)
1064 return 0;
1065 if (starts_with(start, "trunc)"))
1066 c->truncate = trunc_right;
1067 else if (starts_with(start, "ltrunc)"))
1068 c->truncate = trunc_left;
1069 else if (starts_with(start, "mtrunc)"))
1070 c->truncate = trunc_middle;
1071 else
1072 return 0;
1073 } else
1074 c->truncate = trunc_none;
1075
1076 return end - placeholder + 1;
1077 }
1078 return 0;
1079 }
1080
1081 static int match_placeholder_arg_value(const char *to_parse, const char *candidate,
1082 const char **end, const char **valuestart,
1083 size_t *valuelen)
1084 {
1085 const char *p;
1086
1087 if (!(skip_prefix(to_parse, candidate, &p)))
1088 return 0;
1089 if (valuestart) {
1090 if (*p == '=') {
1091 *valuestart = p + 1;
1092 *valuelen = strcspn(*valuestart, ",)");
1093 p = *valuestart + *valuelen;
1094 } else {
1095 if (*p != ',' && *p != ')')
1096 return 0;
1097 *valuestart = NULL;
1098 *valuelen = 0;
1099 }
1100 }
1101 if (*p == ',') {
1102 *end = p + 1;
1103 return 1;
1104 }
1105 if (*p == ')') {
1106 *end = p;
1107 return 1;
1108 }
1109 return 0;
1110 }
1111
1112 static int match_placeholder_bool_arg(const char *to_parse, const char *candidate,
1113 const char **end, int *val)
1114 {
1115 const char *argval;
1116 char *strval;
1117 size_t arglen;
1118 int v;
1119
1120 if (!match_placeholder_arg_value(to_parse, candidate, end, &argval, &arglen))
1121 return 0;
1122
1123 if (!argval) {
1124 *val = 1;
1125 return 1;
1126 }
1127
1128 strval = xstrndup(argval, arglen);
1129 v = git_parse_maybe_bool(strval);
1130 free(strval);
1131
1132 if (v == -1)
1133 return 0;
1134
1135 *val = v;
1136
1137 return 1;
1138 }
1139
1140 static int format_trailer_match_cb(const struct strbuf *key, void *ud)
1141 {
1142 const struct string_list *list = ud;
1143 const struct string_list_item *item;
1144
1145 for_each_string_list_item (item, list) {
1146 if (key->len == (uintptr_t)item->util &&
1147 !strncasecmp(item->string, key->buf, key->len))
1148 return 1;
1149 }
1150 return 0;
1151 }
1152
1153 static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
1154 const char *placeholder,
1155 void *context)
1156 {
1157 struct format_commit_context *c = context;
1158 const struct commit *commit = c->commit;
1159 const char *msg = c->message;
1160 struct commit_list *p;
1161 const char *arg, *eol;
1162 size_t res;
1163 char **slot;
1164
1165 /* these are independent of the commit */
1166 res = strbuf_expand_literal_cb(sb, placeholder, NULL);
1167 if (res)
1168 return res;
1169
1170 switch (placeholder[0]) {
1171 case 'C':
1172 if (starts_with(placeholder + 1, "(auto)")) {
1173 c->auto_color = want_color(c->pretty_ctx->color);
1174 if (c->auto_color && sb->len)
1175 strbuf_addstr(sb, GIT_COLOR_RESET);
1176 return 7; /* consumed 7 bytes, "C(auto)" */
1177 } else {
1178 int ret = parse_color(sb, placeholder, c);
1179 if (ret)
1180 c->auto_color = 0;
1181 /*
1182 * Otherwise, we decided to treat %C<unknown>
1183 * as a literal string, and the previous
1184 * %C(auto) is still valid.
1185 */
1186 return ret;
1187 }
1188 case 'w':
1189 if (placeholder[1] == '(') {
1190 unsigned long width = 0, indent1 = 0, indent2 = 0;
1191 char *next;
1192 const char *start = placeholder + 2;
1193 const char *end = strchr(start, ')');
1194 if (!end)
1195 return 0;
1196 if (end > start) {
1197 width = strtoul(start, &next, 10);
1198 if (*next == ',') {
1199 indent1 = strtoul(next + 1, &next, 10);
1200 if (*next == ',') {
1201 indent2 = strtoul(next + 1,
1202 &next, 10);
1203 }
1204 }
1205 if (*next != ')')
1206 return 0;
1207 }
1208 rewrap_message_tail(sb, c, width, indent1, indent2);
1209 return end - placeholder + 1;
1210 } else
1211 return 0;
1212
1213 case '<':
1214 case '>':
1215 return parse_padding_placeholder(placeholder, c);
1216 }
1217
1218 /* these depend on the commit */
1219 if (!commit->object.parsed)
1220 parse_object(the_repository, &commit->object.oid);
1221
1222 switch (placeholder[0]) {
1223 case 'H': /* commit hash */
1224 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1225 strbuf_addstr(sb, oid_to_hex(&commit->object.oid));
1226 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1227 return 1;
1228 case 'h': /* abbreviated commit hash */
1229 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1230 strbuf_add_unique_abbrev(sb, &commit->object.oid,
1231 c->pretty_ctx->abbrev);
1232 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1233 return 1;
1234 case 'T': /* tree hash */
1235 strbuf_addstr(sb, oid_to_hex(get_commit_tree_oid(commit)));
1236 return 1;
1237 case 't': /* abbreviated tree hash */
1238 strbuf_add_unique_abbrev(sb,
1239 get_commit_tree_oid(commit),
1240 c->pretty_ctx->abbrev);
1241 return 1;
1242 case 'P': /* parent hashes */
1243 for (p = commit->parents; p; p = p->next) {
1244 if (p != commit->parents)
1245 strbuf_addch(sb, ' ');
1246 strbuf_addstr(sb, oid_to_hex(&p->item->object.oid));
1247 }
1248 return 1;
1249 case 'p': /* abbreviated parent hashes */
1250 for (p = commit->parents; p; p = p->next) {
1251 if (p != commit->parents)
1252 strbuf_addch(sb, ' ');
1253 strbuf_add_unique_abbrev(sb, &p->item->object.oid,
1254 c->pretty_ctx->abbrev);
1255 }
1256 return 1;
1257 case 'm': /* left/right/bottom */
1258 strbuf_addstr(sb, get_revision_mark(NULL, commit));
1259 return 1;
1260 case 'd':
1261 format_decorations(sb, commit, c->auto_color);
1262 return 1;
1263 case 'D':
1264 format_decorations_extended(sb, commit, c->auto_color, "", ", ", "");
1265 return 1;
1266 case 'S': /* tag/branch like --source */
1267 if (!(c->pretty_ctx->rev && c->pretty_ctx->rev->sources))
1268 return 0;
1269 slot = revision_sources_at(c->pretty_ctx->rev->sources, commit);
1270 if (!(slot && *slot))
1271 return 0;
1272 strbuf_addstr(sb, *slot);
1273 return 1;
1274 case 'g': /* reflog info */
1275 switch(placeholder[1]) {
1276 case 'd': /* reflog selector */
1277 case 'D':
1278 if (c->pretty_ctx->reflog_info)
1279 get_reflog_selector(sb,
1280 c->pretty_ctx->reflog_info,
1281 &c->pretty_ctx->date_mode,
1282 c->pretty_ctx->date_mode_explicit,
1283 (placeholder[1] == 'd'));
1284 return 2;
1285 case 's': /* reflog message */
1286 if (c->pretty_ctx->reflog_info)
1287 get_reflog_message(sb, c->pretty_ctx->reflog_info);
1288 return 2;
1289 case 'n':
1290 case 'N':
1291 case 'e':
1292 case 'E':
1293 return format_reflog_person(sb,
1294 placeholder[1],
1295 c->pretty_ctx->reflog_info,
1296 &c->pretty_ctx->date_mode);
1297 }
1298 return 0; /* unknown %g placeholder */
1299 case 'N':
1300 if (c->pretty_ctx->notes_message) {
1301 strbuf_addstr(sb, c->pretty_ctx->notes_message);
1302 return 1;
1303 }
1304 return 0;
1305 }
1306
1307 if (placeholder[0] == 'G') {
1308 if (!c->signature_check.result)
1309 check_commit_signature(c->commit, &(c->signature_check));
1310 switch (placeholder[1]) {
1311 case 'G':
1312 if (c->signature_check.gpg_output)
1313 strbuf_addstr(sb, c->signature_check.gpg_output);
1314 break;
1315 case '?':
1316 switch (c->signature_check.result) {
1317 case 'G':
1318 switch (c->signature_check.trust_level) {
1319 case TRUST_UNDEFINED:
1320 case TRUST_NEVER:
1321 strbuf_addch(sb, 'U');
1322 break;
1323 default:
1324 strbuf_addch(sb, 'G');
1325 break;
1326 }
1327 break;
1328 case 'B':
1329 case 'E':
1330 case 'N':
1331 case 'X':
1332 case 'Y':
1333 case 'R':
1334 strbuf_addch(sb, c->signature_check.result);
1335 }
1336 break;
1337 case 'S':
1338 if (c->signature_check.signer)
1339 strbuf_addstr(sb, c->signature_check.signer);
1340 break;
1341 case 'K':
1342 if (c->signature_check.key)
1343 strbuf_addstr(sb, c->signature_check.key);
1344 break;
1345 case 'F':
1346 if (c->signature_check.fingerprint)
1347 strbuf_addstr(sb, c->signature_check.fingerprint);
1348 break;
1349 case 'P':
1350 if (c->signature_check.primary_key_fingerprint)
1351 strbuf_addstr(sb, c->signature_check.primary_key_fingerprint);
1352 break;
1353 case 'T':
1354 switch (c->signature_check.trust_level) {
1355 case TRUST_UNDEFINED:
1356 strbuf_addstr(sb, "undefined");
1357 break;
1358 case TRUST_NEVER:
1359 strbuf_addstr(sb, "never");
1360 break;
1361 case TRUST_MARGINAL:
1362 strbuf_addstr(sb, "marginal");
1363 break;
1364 case TRUST_FULLY:
1365 strbuf_addstr(sb, "fully");
1366 break;
1367 case TRUST_ULTIMATE:
1368 strbuf_addstr(sb, "ultimate");
1369 break;
1370 }
1371 break;
1372 default:
1373 return 0;
1374 }
1375 return 2;
1376 }
1377
1378
1379 /* For the rest we have to parse the commit header. */
1380 if (!c->commit_header_parsed)
1381 parse_commit_header(c);
1382
1383 switch (placeholder[0]) {
1384 case 'a': /* author ... */
1385 return format_person_part(sb, placeholder[1],
1386 msg + c->author.off, c->author.len,
1387 &c->pretty_ctx->date_mode);
1388 case 'c': /* committer ... */
1389 return format_person_part(sb, placeholder[1],
1390 msg + c->committer.off, c->committer.len,
1391 &c->pretty_ctx->date_mode);
1392 case 'e': /* encoding */
1393 if (c->commit_encoding)
1394 strbuf_addstr(sb, c->commit_encoding);
1395 return 1;
1396 case 'B': /* raw body */
1397 /* message_off is always left at the initial newline */
1398 strbuf_addstr(sb, msg + c->message_off + 1);
1399 return 1;
1400 }
1401
1402 /* Now we need to parse the commit message. */
1403 if (!c->commit_message_parsed)
1404 parse_commit_message(c);
1405
1406 switch (placeholder[0]) {
1407 case 's': /* subject */
1408 format_subject(sb, msg + c->subject_off, " ");
1409 return 1;
1410 case 'f': /* sanitized subject */
1411 eol = strchrnul(msg + c->subject_off, '\n');
1412 format_sanitized_subject(sb, msg + c->subject_off, eol - (msg + c->subject_off));
1413 return 1;
1414 case 'b': /* body */
1415 strbuf_addstr(sb, msg + c->body_off);
1416 return 1;
1417 }
1418
1419 if (skip_prefix(placeholder, "(trailers", &arg)) {
1420 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1421 struct string_list filter_list = STRING_LIST_INIT_NODUP;
1422 struct strbuf sepbuf = STRBUF_INIT;
1423 size_t ret = 0;
1424
1425 opts.no_divider = 1;
1426
1427 if (*arg == ':') {
1428 arg++;
1429 for (;;) {
1430 const char *argval;
1431 size_t arglen;
1432
1433 if (match_placeholder_arg_value(arg, "key", &arg, &argval, &arglen)) {
1434 uintptr_t len = arglen;
1435
1436 if (!argval)
1437 goto trailer_out;
1438
1439 if (len && argval[len - 1] == ':')
1440 len--;
1441 string_list_append(&filter_list, argval)->util = (char *)len;
1442
1443 opts.filter = format_trailer_match_cb;
1444 opts.filter_data = &filter_list;
1445 opts.only_trailers = 1;
1446 } else if (match_placeholder_arg_value(arg, "separator", &arg, &argval, &arglen)) {
1447 char *fmt;
1448
1449 strbuf_reset(&sepbuf);
1450 fmt = xstrndup(argval, arglen);
1451 strbuf_expand(&sepbuf, fmt, strbuf_expand_literal_cb, NULL);
1452 free(fmt);
1453 opts.separator = &sepbuf;
1454 } else if (!match_placeholder_bool_arg(arg, "only", &arg, &opts.only_trailers) &&
1455 !match_placeholder_bool_arg(arg, "unfold", &arg, &opts.unfold) &&
1456 !match_placeholder_bool_arg(arg, "valueonly", &arg, &opts.value_only))
1457 break;
1458 }
1459 }
1460 if (*arg == ')') {
1461 format_trailers_from_commit(sb, msg + c->subject_off, &opts);
1462 ret = arg - placeholder + 1;
1463 }
1464 trailer_out:
1465 string_list_clear(&filter_list, 0);
1466 strbuf_release(&sepbuf);
1467 return ret;
1468 }
1469
1470 return 0; /* unknown placeholder */
1471 }
1472
1473 static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */
1474 const char *placeholder,
1475 struct format_commit_context *c)
1476 {
1477 struct strbuf local_sb = STRBUF_INIT;
1478 size_t total_consumed = 0;
1479 int len, padding = c->padding;
1480
1481 if (padding < 0) {
1482 const char *start = strrchr(sb->buf, '\n');
1483 int occupied;
1484 if (!start)
1485 start = sb->buf;
1486 occupied = utf8_strnwidth(start, strlen(start), 1);
1487 occupied += c->pretty_ctx->graph_width;
1488 padding = (-padding) - occupied;
1489 }
1490 while (1) {
1491 int modifier = *placeholder == 'C';
1492 size_t consumed = format_commit_one(&local_sb, placeholder, c);
1493 total_consumed += consumed;
1494
1495 if (!modifier)
1496 break;
1497
1498 placeholder += consumed;
1499 if (*placeholder != '%')
1500 break;
1501 placeholder++;
1502 total_consumed++;
1503 }
1504 len = utf8_strnwidth(local_sb.buf, local_sb.len, 1);
1505
1506 if (c->flush_type == flush_left_and_steal) {
1507 const char *ch = sb->buf + sb->len - 1;
1508 while (len > padding && ch > sb->buf) {
1509 const char *p;
1510 if (*ch == ' ') {
1511 ch--;
1512 padding++;
1513 continue;
1514 }
1515 /* check for trailing ansi sequences */
1516 if (*ch != 'm')
1517 break;
1518 p = ch - 1;
1519 while (p > sb->buf && ch - p < 10 && *p != '\033')
1520 p--;
1521 if (*p != '\033' ||
1522 ch + 1 - p != display_mode_esc_sequence_len(p))
1523 break;
1524 /*
1525 * got a good ansi sequence, put it back to
1526 * local_sb as we're cutting sb
1527 */
1528 strbuf_insert(&local_sb, 0, p, ch + 1 - p);
1529 ch = p - 1;
1530 }
1531 strbuf_setlen(sb, ch + 1 - sb->buf);
1532 c->flush_type = flush_left;
1533 }
1534
1535 if (len > padding) {
1536 switch (c->truncate) {
1537 case trunc_left:
1538 strbuf_utf8_replace(&local_sb,
1539 0, len - (padding - 2),
1540 "..");
1541 break;
1542 case trunc_middle:
1543 strbuf_utf8_replace(&local_sb,
1544 padding / 2 - 1,
1545 len - (padding - 2),
1546 "..");
1547 break;
1548 case trunc_right:
1549 strbuf_utf8_replace(&local_sb,
1550 padding - 2, len - (padding - 2),
1551 "..");
1552 break;
1553 case trunc_none:
1554 break;
1555 }
1556 strbuf_addbuf(sb, &local_sb);
1557 } else {
1558 size_t sb_len = sb->len, offset = 0;
1559 if (c->flush_type == flush_left)
1560 offset = padding - len;
1561 else if (c->flush_type == flush_both)
1562 offset = (padding - len) / 2;
1563 /*
1564 * we calculate padding in columns, now
1565 * convert it back to chars
1566 */
1567 padding = padding - len + local_sb.len;
1568 strbuf_addchars(sb, ' ', padding);
1569 memcpy(sb->buf + sb_len + offset, local_sb.buf,
1570 local_sb.len);
1571 }
1572 strbuf_release(&local_sb);
1573 c->flush_type = no_flush;
1574 return total_consumed;
1575 }
1576
1577 static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */
1578 const char *placeholder,
1579 void *context)
1580 {
1581 size_t consumed, orig_len;
1582 enum {
1583 NO_MAGIC,
1584 ADD_LF_BEFORE_NON_EMPTY,
1585 DEL_LF_BEFORE_EMPTY,
1586 ADD_SP_BEFORE_NON_EMPTY
1587 } magic = NO_MAGIC;
1588
1589 switch (placeholder[0]) {
1590 case '-':
1591 magic = DEL_LF_BEFORE_EMPTY;
1592 break;
1593 case '+':
1594 magic = ADD_LF_BEFORE_NON_EMPTY;
1595 break;
1596 case ' ':
1597 magic = ADD_SP_BEFORE_NON_EMPTY;
1598 break;
1599 default:
1600 break;
1601 }
1602 if (magic != NO_MAGIC) {
1603 placeholder++;
1604
1605 switch (placeholder[0]) {
1606 case 'w':
1607 /*
1608 * `%+w()` cannot ever expand to a non-empty string,
1609 * and it potentially changes the layout of preceding
1610 * contents. We're thus not able to handle the magic in
1611 * this combination and refuse the pattern.
1612 */
1613 return 0;
1614 };
1615 }
1616
1617 orig_len = sb->len;
1618 if (((struct format_commit_context *)context)->flush_type != no_flush)
1619 consumed = format_and_pad_commit(sb, placeholder, context);
1620 else
1621 consumed = format_commit_one(sb, placeholder, context);
1622 if (magic == NO_MAGIC)
1623 return consumed;
1624
1625 if ((orig_len == sb->len) && magic == DEL_LF_BEFORE_EMPTY) {
1626 while (sb->len && sb->buf[sb->len - 1] == '\n')
1627 strbuf_setlen(sb, sb->len - 1);
1628 } else if (orig_len != sb->len) {
1629 if (magic == ADD_LF_BEFORE_NON_EMPTY)
1630 strbuf_insertstr(sb, orig_len, "\n");
1631 else if (magic == ADD_SP_BEFORE_NON_EMPTY)
1632 strbuf_insertstr(sb, orig_len, " ");
1633 }
1634 return consumed + 1;
1635 }
1636
1637 static size_t userformat_want_item(struct strbuf *sb, const char *placeholder,
1638 void *context)
1639 {
1640 struct userformat_want *w = context;
1641
1642 if (*placeholder == '+' || *placeholder == '-' || *placeholder == ' ')
1643 placeholder++;
1644
1645 switch (*placeholder) {
1646 case 'N':
1647 w->notes = 1;
1648 break;
1649 case 'S':
1650 w->source = 1;
1651 break;
1652 }
1653 return 0;
1654 }
1655
1656 void userformat_find_requirements(const char *fmt, struct userformat_want *w)
1657 {
1658 struct strbuf dummy = STRBUF_INIT;
1659
1660 if (!fmt) {
1661 if (!user_format)
1662 return;
1663 fmt = user_format;
1664 }
1665 strbuf_expand(&dummy, fmt, userformat_want_item, w);
1666 strbuf_release(&dummy);
1667 }
1668
1669 void repo_format_commit_message(struct repository *r,
1670 const struct commit *commit,
1671 const char *format, struct strbuf *sb,
1672 const struct pretty_print_context *pretty_ctx)
1673 {
1674 struct format_commit_context context = {
1675 .commit = commit,
1676 .pretty_ctx = pretty_ctx,
1677 .wrap_start = sb->len
1678 };
1679 const char *output_enc = pretty_ctx->output_encoding;
1680 const char *utf8 = "UTF-8";
1681
1682 /*
1683 * convert a commit message to UTF-8 first
1684 * as far as 'format_commit_item' assumes it in UTF-8
1685 */
1686 context.message = repo_logmsg_reencode(r, commit,
1687 &context.commit_encoding,
1688 utf8);
1689
1690 strbuf_expand(sb, format, format_commit_item, &context);
1691 rewrap_message_tail(sb, &context, 0, 0, 0);
1692
1693 /* then convert a commit message to an actual output encoding */
1694 if (output_enc) {
1695 if (same_encoding(utf8, output_enc))
1696 output_enc = NULL;
1697 } else {
1698 if (context.commit_encoding &&
1699 !same_encoding(context.commit_encoding, utf8))
1700 output_enc = context.commit_encoding;
1701 }
1702
1703 if (output_enc) {
1704 size_t outsz;
1705 char *out = reencode_string_len(sb->buf, sb->len,
1706 output_enc, utf8, &outsz);
1707 if (out)
1708 strbuf_attach(sb, out, outsz, outsz + 1);
1709 }
1710
1711 free(context.commit_encoding);
1712 repo_unuse_commit_buffer(r, commit, context.message);
1713 }
1714
1715 static void pp_header(struct pretty_print_context *pp,
1716 const char *encoding,
1717 const struct commit *commit,
1718 const char **msg_p,
1719 struct strbuf *sb)
1720 {
1721 int parents_shown = 0;
1722
1723 for (;;) {
1724 const char *name, *line = *msg_p;
1725 int linelen = get_one_line(*msg_p);
1726
1727 if (!linelen)
1728 return;
1729 *msg_p += linelen;
1730
1731 if (linelen == 1)
1732 /* End of header */
1733 return;
1734
1735 if (pp->fmt == CMIT_FMT_RAW) {
1736 strbuf_add(sb, line, linelen);
1737 continue;
1738 }
1739
1740 if (starts_with(line, "parent ")) {
1741 if (linelen != the_hash_algo->hexsz + 8)
1742 die("bad parent line in commit");
1743 continue;
1744 }
1745
1746 if (!parents_shown) {
1747 unsigned num = commit_list_count(commit->parents);
1748 /* with enough slop */
1749 strbuf_grow(sb, num * (GIT_MAX_HEXSZ + 10) + 20);
1750 add_merge_info(pp, sb, commit);
1751 parents_shown = 1;
1752 }
1753
1754 /*
1755 * MEDIUM == DEFAULT shows only author with dates.
1756 * FULL shows both authors but not dates.
1757 * FULLER shows both authors and dates.
1758 */
1759 if (skip_prefix(line, "author ", &name)) {
1760 strbuf_grow(sb, linelen + 80);
1761 pp_user_info(pp, "Author", sb, name, encoding);
1762 }
1763 if (skip_prefix(line, "committer ", &name) &&
1764 (pp->fmt == CMIT_FMT_FULL || pp->fmt == CMIT_FMT_FULLER)) {
1765 strbuf_grow(sb, linelen + 80);
1766 pp_user_info(pp, "Commit", sb, name, encoding);
1767 }
1768 }
1769 }
1770
1771 void pp_title_line(struct pretty_print_context *pp,
1772 const char **msg_p,
1773 struct strbuf *sb,
1774 const char *encoding,
1775 int need_8bit_cte)
1776 {
1777 static const int max_length = 78; /* per rfc2047 */
1778 struct strbuf title;
1779
1780 strbuf_init(&title, 80);
1781 *msg_p = format_subject(&title, *msg_p,
1782 pp->preserve_subject ? "\n" : " ");
1783
1784 strbuf_grow(sb, title.len + 1024);
1785 if (pp->print_email_subject) {
1786 if (pp->rev)
1787 fmt_output_email_subject(sb, pp->rev);
1788 if (pp->encode_email_headers &&
1789 needs_rfc2047_encoding(title.buf, title.len))
1790 add_rfc2047(sb, title.buf, title.len,
1791 encoding, RFC2047_SUBJECT);
1792 else
1793 strbuf_add_wrapped_bytes(sb, title.buf, title.len,
1794 -last_line_length(sb), 1, max_length);
1795 } else {
1796 strbuf_addbuf(sb, &title);
1797 }
1798 strbuf_addch(sb, '\n');
1799
1800 if (need_8bit_cte == 0) {
1801 int i;
1802 for (i = 0; i < pp->in_body_headers.nr; i++) {
1803 if (has_non_ascii(pp->in_body_headers.items[i].string)) {
1804 need_8bit_cte = 1;
1805 break;
1806 }
1807 }
1808 }
1809
1810 if (need_8bit_cte > 0) {
1811 const char *header_fmt =
1812 "MIME-Version: 1.0\n"
1813 "Content-Type: text/plain; charset=%s\n"
1814 "Content-Transfer-Encoding: 8bit\n";
1815 strbuf_addf(sb, header_fmt, encoding);
1816 }
1817 if (pp->after_subject) {
1818 strbuf_addstr(sb, pp->after_subject);
1819 }
1820 if (cmit_fmt_is_mail(pp->fmt)) {
1821 strbuf_addch(sb, '\n');
1822 }
1823
1824 if (pp->in_body_headers.nr) {
1825 int i;
1826 for (i = 0; i < pp->in_body_headers.nr; i++) {
1827 strbuf_addstr(sb, pp->in_body_headers.items[i].string);
1828 free(pp->in_body_headers.items[i].string);
1829 }
1830 string_list_clear(&pp->in_body_headers, 0);
1831 strbuf_addch(sb, '\n');
1832 }
1833
1834 strbuf_release(&title);
1835 }
1836
1837 static int pp_utf8_width(const char *start, const char *end)
1838 {
1839 int width = 0;
1840 size_t remain = end - start;
1841
1842 while (remain) {
1843 int n = utf8_width(&start, &remain);
1844 if (n < 0 || !start)
1845 return -1;
1846 width += n;
1847 }
1848 return width;
1849 }
1850
1851 static void strbuf_add_tabexpand(struct strbuf *sb, int tabwidth,
1852 const char *line, int linelen)
1853 {
1854 const char *tab;
1855
1856 while ((tab = memchr(line, '\t', linelen)) != NULL) {
1857 int width = pp_utf8_width(line, tab);
1858
1859 /*
1860 * If it wasn't well-formed utf8, or it
1861 * had characters with badly defined
1862 * width (control characters etc), just
1863 * give up on trying to align things.
1864 */
1865 if (width < 0)
1866 break;
1867
1868 /* Output the data .. */
1869 strbuf_add(sb, line, tab - line);
1870
1871 /* .. and the de-tabified tab */
1872 strbuf_addchars(sb, ' ', tabwidth - (width % tabwidth));
1873
1874 /* Skip over the printed part .. */
1875 linelen -= tab + 1 - line;
1876 line = tab + 1;
1877 }
1878
1879 /*
1880 * Print out everything after the last tab without
1881 * worrying about width - there's nothing more to
1882 * align.
1883 */
1884 strbuf_add(sb, line, linelen);
1885 }
1886
1887 /*
1888 * pp_handle_indent() prints out the intendation, and
1889 * the whole line (without the final newline), after
1890 * de-tabifying.
1891 */
1892 static void pp_handle_indent(struct pretty_print_context *pp,
1893 struct strbuf *sb, int indent,
1894 const char *line, int linelen)
1895 {
1896 strbuf_addchars(sb, ' ', indent);
1897 if (pp->expand_tabs_in_log)
1898 strbuf_add_tabexpand(sb, pp->expand_tabs_in_log, line, linelen);
1899 else
1900 strbuf_add(sb, line, linelen);
1901 }
1902
1903 static int is_mboxrd_from(const char *line, int len)
1904 {
1905 /*
1906 * a line matching /^From $/ here would only have len == 4
1907 * at this point because is_empty_line would've trimmed all
1908 * trailing space
1909 */
1910 return len > 4 && starts_with(line + strspn(line, ">"), "From ");
1911 }
1912
1913 void pp_remainder(struct pretty_print_context *pp,
1914 const char **msg_p,
1915 struct strbuf *sb,
1916 int indent)
1917 {
1918 int first = 1;
1919 for (;;) {
1920 const char *line = *msg_p;
1921 int linelen = get_one_line(line);
1922 *msg_p += linelen;
1923
1924 if (!linelen)
1925 break;
1926
1927 if (is_blank_line(line, &linelen)) {
1928 if (first)
1929 continue;
1930 if (pp->fmt == CMIT_FMT_SHORT)
1931 break;
1932 }
1933 first = 0;
1934
1935 strbuf_grow(sb, linelen + indent + 20);
1936 if (indent)
1937 pp_handle_indent(pp, sb, indent, line, linelen);
1938 else if (pp->expand_tabs_in_log)
1939 strbuf_add_tabexpand(sb, pp->expand_tabs_in_log,
1940 line, linelen);
1941 else {
1942 if (pp->fmt == CMIT_FMT_MBOXRD &&
1943 is_mboxrd_from(line, linelen))
1944 strbuf_addch(sb, '>');
1945
1946 strbuf_add(sb, line, linelen);
1947 }
1948 strbuf_addch(sb, '\n');
1949 }
1950 }
1951
1952 void pretty_print_commit(struct pretty_print_context *pp,
1953 const struct commit *commit,
1954 struct strbuf *sb)
1955 {
1956 unsigned long beginning_of_body;
1957 int indent = 4;
1958 const char *msg;
1959 const char *reencoded;
1960 const char *encoding;
1961 int need_8bit_cte = pp->need_8bit_cte;
1962
1963 if (pp->fmt == CMIT_FMT_USERFORMAT) {
1964 format_commit_message(commit, user_format, sb, pp);
1965 return;
1966 }
1967
1968 encoding = get_log_output_encoding();
1969 msg = reencoded = logmsg_reencode(commit, NULL, encoding);
1970
1971 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
1972 indent = 0;
1973
1974 /*
1975 * We need to check and emit Content-type: to mark it
1976 * as 8-bit if we haven't done so.
1977 */
1978 if (cmit_fmt_is_mail(pp->fmt) && need_8bit_cte == 0) {
1979 int i, ch, in_body;
1980
1981 for (in_body = i = 0; (ch = msg[i]); i++) {
1982 if (!in_body) {
1983 /* author could be non 7-bit ASCII but
1984 * the log may be so; skip over the
1985 * header part first.
1986 */
1987 if (ch == '\n' && msg[i+1] == '\n')
1988 in_body = 1;
1989 }
1990 else if (non_ascii(ch)) {
1991 need_8bit_cte = 1;
1992 break;
1993 }
1994 }
1995 }
1996
1997 pp_header(pp, encoding, commit, &msg, sb);
1998 if (pp->fmt != CMIT_FMT_ONELINE && !pp->print_email_subject) {
1999 strbuf_addch(sb, '\n');
2000 }
2001
2002 /* Skip excess blank lines at the beginning of body, if any... */
2003 msg = skip_blank_lines(msg);
2004
2005 /* These formats treat the title line specially. */
2006 if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
2007 pp_title_line(pp, &msg, sb, encoding, need_8bit_cte);
2008
2009 beginning_of_body = sb->len;
2010 if (pp->fmt != CMIT_FMT_ONELINE)
2011 pp_remainder(pp, &msg, sb, indent);
2012 strbuf_rtrim(sb);
2013
2014 /* Make sure there is an EOLN for the non-oneline case */
2015 if (pp->fmt != CMIT_FMT_ONELINE)
2016 strbuf_addch(sb, '\n');
2017
2018 /*
2019 * The caller may append additional body text in e-mail
2020 * format. Make sure we did not strip the blank line
2021 * between the header and the body.
2022 */
2023 if (cmit_fmt_is_mail(pp->fmt) && sb->len <= beginning_of_body)
2024 strbuf_addch(sb, '\n');
2025
2026 unuse_commit_buffer(commit, reencoded);
2027 }
2028
2029 void pp_commit_easy(enum cmit_fmt fmt, const struct commit *commit,
2030 struct strbuf *sb)
2031 {
2032 struct pretty_print_context pp = {0};
2033 pp.fmt = fmt;
2034 pretty_print_commit(&pp, commit, sb);
2035 }