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