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