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