mailinfo: do not concatenate charset= attribute values from mime headers
[git.git] / builtin / mailinfo.c
blobdd8b67cfaafb15272d424fb01ead8b51276ec957
1 /*
2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
4 */
5 #include "cache.h"
6 #include "builtin.h"
7 #include "utf8.h"
8 #include "strbuf.h"
10 static FILE *cmitmsg, *patchfile, *fin, *fout;
12 static int keep_subject;
13 static int keep_non_patch_brackets_in_subject;
14 static const char *metainfo_charset;
15 static struct strbuf line = STRBUF_INIT;
16 static struct strbuf name = STRBUF_INIT;
17 static struct strbuf email = STRBUF_INIT;
19 static enum {
20 TE_DONTCARE, TE_QP, TE_BASE64
21 } transfer_encoding;
22 static enum {
23 TYPE_TEXT, TYPE_OTHER
24 } message_type;
26 static struct strbuf charset = STRBUF_INIT;
27 static int patch_lines;
28 static struct strbuf **p_hdr_data, **s_hdr_data;
29 static int use_scissors;
30 static int use_inbody_headers = 1;
32 #define MAX_HDR_PARSED 10
33 #define MAX_BOUNDARIES 5
35 static void cleanup_space(struct strbuf *sb);
38 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
40 struct strbuf *src = name;
41 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
42 strchr(name->buf, '<') || strchr(name->buf, '>'))
43 src = email;
44 else if (name == out)
45 return;
46 strbuf_reset(out);
47 strbuf_addbuf(out, src);
50 static void parse_bogus_from(const struct strbuf *line)
52 /* John Doe <johndoe> */
54 char *bra, *ket;
55 /* This is fallback, so do not bother if we already have an
56 * e-mail address.
58 if (email.len)
59 return;
61 bra = strchr(line->buf, '<');
62 if (!bra)
63 return;
64 ket = strchr(bra, '>');
65 if (!ket)
66 return;
68 strbuf_reset(&email);
69 strbuf_add(&email, bra + 1, ket - bra - 1);
71 strbuf_reset(&name);
72 strbuf_add(&name, line->buf, bra - line->buf);
73 strbuf_trim(&name);
74 get_sane_name(&name, &name, &email);
77 static void handle_from(const struct strbuf *from)
79 char *at;
80 size_t el;
81 struct strbuf f;
83 strbuf_init(&f, from->len);
84 strbuf_addbuf(&f, from);
86 at = strchr(f.buf, '@');
87 if (!at) {
88 parse_bogus_from(from);
89 return;
93 * If we already have one email, don't take any confusing lines
95 if (email.len && strchr(at + 1, '@')) {
96 strbuf_release(&f);
97 return;
100 /* Pick up the string around '@', possibly delimited with <>
101 * pair; that is the email part.
103 while (at > f.buf) {
104 char c = at[-1];
105 if (isspace(c))
106 break;
107 if (c == '<') {
108 at[-1] = ' ';
109 break;
111 at--;
113 el = strcspn(at, " \n\t\r\v\f>");
114 strbuf_reset(&email);
115 strbuf_add(&email, at, el);
116 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
118 /* The remainder is name. It could be
120 * - "John Doe <john.doe@xz>" (a), or
121 * - "john.doe@xz (John Doe)" (b), or
122 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
124 * but we have removed the email part, so
126 * - remove extra spaces which could stay after email (case 'c'), and
127 * - trim from both ends, possibly removing the () pair at the end
128 * (cases 'a' and 'b').
130 cleanup_space(&f);
131 strbuf_trim(&f);
132 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
133 strbuf_remove(&f, 0, 1);
134 strbuf_setlen(&f, f.len - 1);
137 get_sane_name(&name, &f, &email);
138 strbuf_release(&f);
141 static void handle_header(struct strbuf **out, const struct strbuf *line)
143 if (!*out) {
144 *out = xmalloc(sizeof(struct strbuf));
145 strbuf_init(*out, line->len);
146 } else
147 strbuf_reset(*out);
149 strbuf_addbuf(*out, line);
152 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
153 * to have enough heuristics to grok MIME encoded patches often found
154 * on our mailing lists. For example, we do not even treat header lines
155 * case insensitively.
158 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
160 const char *ends, *ap = strcasestr(line, name);
161 size_t sz;
163 strbuf_setlen(attr, 0);
164 if (!ap)
165 return 0;
166 ap += strlen(name);
167 if (*ap == '"') {
168 ap++;
169 ends = "\"";
171 else
172 ends = "; \t";
173 sz = strcspn(ap, ends);
174 strbuf_add(attr, ap, sz);
175 return 1;
178 static struct strbuf *content[MAX_BOUNDARIES];
180 static struct strbuf **content_top = content;
182 static void handle_content_type(struct strbuf *line)
184 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
185 strbuf_init(boundary, line->len);
187 if (!strcasestr(line->buf, "text/"))
188 message_type = TYPE_OTHER;
189 if (slurp_attr(line->buf, "boundary=", boundary)) {
190 strbuf_insert(boundary, 0, "--", 2);
191 if (++content_top > &content[MAX_BOUNDARIES]) {
192 fprintf(stderr, "Too many boundaries to handle\n");
193 exit(1);
195 *content_top = boundary;
196 boundary = NULL;
198 slurp_attr(line->buf, "charset=", &charset);
200 if (boundary) {
201 strbuf_release(boundary);
202 free(boundary);
206 static void handle_content_transfer_encoding(const struct strbuf *line)
208 if (strcasestr(line->buf, "base64"))
209 transfer_encoding = TE_BASE64;
210 else if (strcasestr(line->buf, "quoted-printable"))
211 transfer_encoding = TE_QP;
212 else
213 transfer_encoding = TE_DONTCARE;
216 static int is_multipart_boundary(const struct strbuf *line)
218 return (((*content_top)->len <= line->len) &&
219 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
222 static void cleanup_subject(struct strbuf *subject)
224 size_t at = 0;
226 while (at < subject->len) {
227 char *pos;
228 size_t remove;
230 switch (subject->buf[at]) {
231 case 'r': case 'R':
232 if (subject->len <= at + 3)
233 break;
234 if (!memcmp(subject->buf + at + 1, "e:", 2)) {
235 strbuf_remove(subject, at, 3);
236 continue;
238 at++;
239 break;
240 case ' ': case '\t': case ':':
241 strbuf_remove(subject, at, 1);
242 continue;
243 case '[':
244 pos = strchr(subject->buf + at, ']');
245 if (!pos)
246 break;
247 remove = pos - subject->buf + at + 1;
248 if (!keep_non_patch_brackets_in_subject ||
249 (7 <= remove &&
250 memmem(subject->buf + at, remove, "PATCH", 5)))
251 strbuf_remove(subject, at, remove);
252 else {
253 at += remove;
255 * If the input had a space after the ], keep
256 * it. We don't bother with finding the end of
257 * the space, since we later normalize it
258 * anyway.
260 if (isspace(subject->buf[at]))
261 at += 1;
263 continue;
265 break;
267 strbuf_trim(subject);
270 static void cleanup_space(struct strbuf *sb)
272 size_t pos, cnt;
273 for (pos = 0; pos < sb->len; pos++) {
274 if (isspace(sb->buf[pos])) {
275 sb->buf[pos] = ' ';
276 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
277 strbuf_remove(sb, pos + 1, cnt);
282 static void decode_header(struct strbuf *line);
283 static const char *header[MAX_HDR_PARSED] = {
284 "From","Subject","Date",
287 static inline int cmp_header(const struct strbuf *line, const char *hdr)
289 int len = strlen(hdr);
290 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
291 line->buf[len] == ':' && isspace(line->buf[len + 1]);
294 static int check_header(const struct strbuf *line,
295 struct strbuf *hdr_data[], int overwrite)
297 int i, ret = 0, len;
298 struct strbuf sb = STRBUF_INIT;
299 /* search for the interesting parts */
300 for (i = 0; header[i]; i++) {
301 int len = strlen(header[i]);
302 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
303 /* Unwrap inline B and Q encoding, and optionally
304 * normalize the meta information to utf8.
306 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
307 decode_header(&sb);
308 handle_header(&hdr_data[i], &sb);
309 ret = 1;
310 goto check_header_out;
314 /* Content stuff */
315 if (cmp_header(line, "Content-Type")) {
316 len = strlen("Content-Type: ");
317 strbuf_add(&sb, line->buf + len, line->len - len);
318 decode_header(&sb);
319 strbuf_insert(&sb, 0, "Content-Type: ", len);
320 handle_content_type(&sb);
321 ret = 1;
322 goto check_header_out;
324 if (cmp_header(line, "Content-Transfer-Encoding")) {
325 len = strlen("Content-Transfer-Encoding: ");
326 strbuf_add(&sb, line->buf + len, line->len - len);
327 decode_header(&sb);
328 handle_content_transfer_encoding(&sb);
329 ret = 1;
330 goto check_header_out;
333 /* for inbody stuff */
334 if (!prefixcmp(line->buf, ">From") && isspace(line->buf[5])) {
335 ret = 1; /* Should this return 0? */
336 goto check_header_out;
338 if (!prefixcmp(line->buf, "[PATCH]") && isspace(line->buf[7])) {
339 for (i = 0; header[i]; i++) {
340 if (!memcmp("Subject", header[i], 7)) {
341 handle_header(&hdr_data[i], line);
342 ret = 1;
343 goto check_header_out;
348 check_header_out:
349 strbuf_release(&sb);
350 return ret;
353 static int is_rfc2822_header(const struct strbuf *line)
356 * The section that defines the loosest possible
357 * field name is "3.6.8 Optional fields".
359 * optional-field = field-name ":" unstructured CRLF
360 * field-name = 1*ftext
361 * ftext = %d33-57 / %59-126
363 int ch;
364 char *cp = line->buf;
366 /* Count mbox From headers as headers */
367 if (!prefixcmp(cp, "From ") || !prefixcmp(cp, ">From "))
368 return 1;
370 while ((ch = *cp++)) {
371 if (ch == ':')
372 return 1;
373 if ((33 <= ch && ch <= 57) ||
374 (59 <= ch && ch <= 126))
375 continue;
376 break;
378 return 0;
381 static int read_one_header_line(struct strbuf *line, FILE *in)
383 /* Get the first part of the line. */
384 if (strbuf_getline(line, in, '\n'))
385 return 0;
388 * Is it an empty line or not a valid rfc2822 header?
389 * If so, stop here, and return false ("not a header")
391 strbuf_rtrim(line);
392 if (!line->len || !is_rfc2822_header(line)) {
393 /* Re-add the newline */
394 strbuf_addch(line, '\n');
395 return 0;
399 * Now we need to eat all the continuation lines..
400 * Yuck, 2822 header "folding"
402 for (;;) {
403 int peek;
404 struct strbuf continuation = STRBUF_INIT;
406 peek = fgetc(in); ungetc(peek, in);
407 if (peek != ' ' && peek != '\t')
408 break;
409 if (strbuf_getline(&continuation, in, '\n'))
410 break;
411 continuation.buf[0] = ' ';
412 strbuf_rtrim(&continuation);
413 strbuf_addbuf(line, &continuation);
416 return 1;
419 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
421 const char *in = q_seg->buf;
422 int c;
423 struct strbuf *out = xmalloc(sizeof(struct strbuf));
424 strbuf_init(out, q_seg->len);
426 while ((c = *in++) != 0) {
427 if (c == '=') {
428 int d = *in++;
429 if (d == '\n' || !d)
430 break; /* drop trailing newline */
431 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
432 continue;
434 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
435 c = 0x20;
436 strbuf_addch(out, c);
438 return out;
441 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
443 /* Decode in..ep, possibly in-place to ot */
444 int c, pos = 0, acc = 0;
445 const char *in = b_seg->buf;
446 struct strbuf *out = xmalloc(sizeof(struct strbuf));
447 strbuf_init(out, b_seg->len);
449 while ((c = *in++) != 0) {
450 if (c == '+')
451 c = 62;
452 else if (c == '/')
453 c = 63;
454 else if ('A' <= c && c <= 'Z')
455 c -= 'A';
456 else if ('a' <= c && c <= 'z')
457 c -= 'a' - 26;
458 else if ('0' <= c && c <= '9')
459 c -= '0' - 52;
460 else
461 continue; /* garbage */
462 switch (pos++) {
463 case 0:
464 acc = (c << 2);
465 break;
466 case 1:
467 strbuf_addch(out, (acc | (c >> 4)));
468 acc = (c & 15) << 4;
469 break;
470 case 2:
471 strbuf_addch(out, (acc | (c >> 2)));
472 acc = (c & 3) << 6;
473 break;
474 case 3:
475 strbuf_addch(out, (acc | c));
476 acc = pos = 0;
477 break;
480 return out;
484 * When there is no known charset, guess.
486 * Right now we assume that if the target is UTF-8 (the default),
487 * and it already looks like UTF-8 (which includes US-ASCII as its
488 * subset, of course) then that is what it is and there is nothing
489 * to do.
491 * Otherwise, we default to assuming it is Latin1 for historical
492 * reasons.
494 static const char *guess_charset(const struct strbuf *line, const char *target_charset)
496 if (is_encoding_utf8(target_charset)) {
497 if (is_utf8(line->buf))
498 return NULL;
500 return "ISO8859-1";
503 static void convert_to_utf8(struct strbuf *line, const char *charset)
505 char *out;
507 if (!charset || !*charset) {
508 charset = guess_charset(line, metainfo_charset);
509 if (!charset)
510 return;
513 if (!strcasecmp(metainfo_charset, charset))
514 return;
515 out = reencode_string(line->buf, metainfo_charset, charset);
516 if (!out)
517 die("cannot convert from %s to %s",
518 charset, metainfo_charset);
519 strbuf_attach(line, out, strlen(out), strlen(out));
522 static int decode_header_bq(struct strbuf *it)
524 char *in, *ep, *cp;
525 struct strbuf outbuf = STRBUF_INIT, *dec;
526 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
527 int rfc2047 = 0;
529 in = it->buf;
530 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
531 int encoding;
532 strbuf_reset(&charset_q);
533 strbuf_reset(&piecebuf);
534 rfc2047 = 1;
536 if (in != ep) {
538 * We are about to process an encoded-word
539 * that begins at ep, but there is something
540 * before the encoded word.
542 char *scan;
543 for (scan = in; scan < ep; scan++)
544 if (!isspace(*scan))
545 break;
547 if (scan != ep || in == it->buf) {
549 * We should not lose that "something",
550 * unless we have just processed an
551 * encoded-word, and there is only LWS
552 * before the one we are about to process.
554 strbuf_add(&outbuf, in, ep - in);
557 /* E.g.
558 * ep : "=?iso-2022-jp?B?GyR...?= foo"
559 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
561 ep += 2;
563 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
564 goto decode_header_bq_out;
566 if (cp + 3 - it->buf > it->len)
567 goto decode_header_bq_out;
568 strbuf_add(&charset_q, ep, cp - ep);
570 encoding = cp[1];
571 if (!encoding || cp[2] != '?')
572 goto decode_header_bq_out;
573 ep = strstr(cp + 3, "?=");
574 if (!ep)
575 goto decode_header_bq_out;
576 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
577 switch (tolower(encoding)) {
578 default:
579 goto decode_header_bq_out;
580 case 'b':
581 dec = decode_b_segment(&piecebuf);
582 break;
583 case 'q':
584 dec = decode_q_segment(&piecebuf, 1);
585 break;
587 if (metainfo_charset)
588 convert_to_utf8(dec, charset_q.buf);
590 strbuf_addbuf(&outbuf, dec);
591 strbuf_release(dec);
592 free(dec);
593 in = ep + 2;
595 strbuf_addstr(&outbuf, in);
596 strbuf_reset(it);
597 strbuf_addbuf(it, &outbuf);
598 decode_header_bq_out:
599 strbuf_release(&outbuf);
600 strbuf_release(&charset_q);
601 strbuf_release(&piecebuf);
602 return rfc2047;
605 static void decode_header(struct strbuf *it)
607 if (decode_header_bq(it))
608 return;
609 /* otherwise "it" is a straight copy of the input.
610 * This can be binary guck but there is no charset specified.
612 if (metainfo_charset)
613 convert_to_utf8(it, "");
616 static void decode_transfer_encoding(struct strbuf *line)
618 struct strbuf *ret;
620 switch (transfer_encoding) {
621 case TE_QP:
622 ret = decode_q_segment(line, 0);
623 break;
624 case TE_BASE64:
625 ret = decode_b_segment(line);
626 break;
627 case TE_DONTCARE:
628 default:
629 return;
631 strbuf_reset(line);
632 strbuf_addbuf(line, ret);
633 strbuf_release(ret);
634 free(ret);
637 static void handle_filter(struct strbuf *line);
639 static int find_boundary(void)
641 while (!strbuf_getline(&line, fin, '\n')) {
642 if (*content_top && is_multipart_boundary(&line))
643 return 1;
645 return 0;
648 static int handle_boundary(void)
650 struct strbuf newline = STRBUF_INIT;
652 strbuf_addch(&newline, '\n');
653 again:
654 if (line.len >= (*content_top)->len + 2 &&
655 !memcmp(line.buf + (*content_top)->len, "--", 2)) {
656 /* we hit an end boundary */
657 /* pop the current boundary off the stack */
658 strbuf_release(*content_top);
659 free(*content_top);
660 *content_top = NULL;
662 /* technically won't happen as is_multipart_boundary()
663 will fail first. But just in case..
665 if (--content_top < content) {
666 fprintf(stderr, "Detected mismatched boundaries, "
667 "can't recover\n");
668 exit(1);
670 handle_filter(&newline);
671 strbuf_release(&newline);
673 /* skip to the next boundary */
674 if (!find_boundary())
675 return 0;
676 goto again;
679 /* set some defaults */
680 transfer_encoding = TE_DONTCARE;
681 strbuf_reset(&charset);
682 message_type = TYPE_TEXT;
684 /* slurp in this section's info */
685 while (read_one_header_line(&line, fin))
686 check_header(&line, p_hdr_data, 0);
688 strbuf_release(&newline);
689 /* replenish line */
690 if (strbuf_getline(&line, fin, '\n'))
691 return 0;
692 strbuf_addch(&line, '\n');
693 return 1;
696 static inline int patchbreak(const struct strbuf *line)
698 size_t i;
700 /* Beginning of a "diff -" header? */
701 if (!prefixcmp(line->buf, "diff -"))
702 return 1;
704 /* CVS "Index: " line? */
705 if (!prefixcmp(line->buf, "Index: "))
706 return 1;
709 * "--- <filename>" starts patches without headers
710 * "---<sp>*" is a manual separator
712 if (line->len < 4)
713 return 0;
715 if (!prefixcmp(line->buf, "---")) {
716 /* space followed by a filename? */
717 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
718 return 1;
719 /* Just whitespace? */
720 for (i = 3; i < line->len; i++) {
721 unsigned char c = line->buf[i];
722 if (c == '\n')
723 return 1;
724 if (!isspace(c))
725 break;
727 return 0;
729 return 0;
732 static int is_scissors_line(const struct strbuf *line)
734 size_t i, len = line->len;
735 int scissors = 0, gap = 0;
736 int first_nonblank = -1;
737 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
738 const char *buf = line->buf;
740 for (i = 0; i < len; i++) {
741 if (isspace(buf[i])) {
742 if (in_perforation) {
743 perforation++;
744 gap++;
746 continue;
748 last_nonblank = i;
749 if (first_nonblank < 0)
750 first_nonblank = i;
751 if (buf[i] == '-') {
752 in_perforation = 1;
753 perforation++;
754 continue;
756 if (i + 1 < len &&
757 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
758 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
759 in_perforation = 1;
760 perforation += 2;
761 scissors += 2;
762 i++;
763 continue;
765 in_perforation = 0;
769 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
770 * Even though there can be arbitrary cruft on the same line
771 * (e.g. "cut here"), in order to avoid misidentification, the
772 * perforation must occupy more than a third of the visible
773 * width of the line, and dashes and scissors must occupy more
774 * than half of the perforation.
777 visible = last_nonblank - first_nonblank + 1;
778 return (scissors && 8 <= visible &&
779 visible < perforation * 3 &&
780 gap * 2 < perforation);
783 static int handle_commit_msg(struct strbuf *line)
785 static int still_looking = 1;
787 if (!cmitmsg)
788 return 0;
790 if (still_looking) {
791 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
792 return 0;
795 if (use_inbody_headers && still_looking) {
796 still_looking = check_header(line, s_hdr_data, 0);
797 if (still_looking)
798 return 0;
799 } else
800 /* Only trim the first (blank) line of the commit message
801 * when ignoring in-body headers.
803 still_looking = 0;
805 /* normalize the log message to UTF-8. */
806 if (metainfo_charset)
807 convert_to_utf8(line, charset.buf);
809 if (use_scissors && is_scissors_line(line)) {
810 int i;
811 if (fseek(cmitmsg, 0L, SEEK_SET))
812 die_errno("Could not rewind output message file");
813 if (ftruncate(fileno(cmitmsg), 0))
814 die_errno("Could not truncate output message file at scissors");
815 still_looking = 1;
818 * We may have already read "secondary headers"; purge
819 * them to give ourselves a clean restart.
821 for (i = 0; header[i]; i++) {
822 if (s_hdr_data[i])
823 strbuf_release(s_hdr_data[i]);
824 s_hdr_data[i] = NULL;
826 return 0;
829 if (patchbreak(line)) {
830 fclose(cmitmsg);
831 cmitmsg = NULL;
832 return 1;
835 fputs(line->buf, cmitmsg);
836 return 0;
839 static void handle_patch(const struct strbuf *line)
841 fwrite(line->buf, 1, line->len, patchfile);
842 patch_lines++;
845 static void handle_filter(struct strbuf *line)
847 static int filter = 0;
849 /* filter tells us which part we left off on */
850 switch (filter) {
851 case 0:
852 if (!handle_commit_msg(line))
853 break;
854 filter++;
855 case 1:
856 handle_patch(line);
857 break;
861 static void handle_body(void)
863 struct strbuf prev = STRBUF_INIT;
865 /* Skip up to the first boundary */
866 if (*content_top) {
867 if (!find_boundary())
868 goto handle_body_out;
871 do {
872 /* process any boundary lines */
873 if (*content_top && is_multipart_boundary(&line)) {
874 /* flush any leftover */
875 if (prev.len) {
876 handle_filter(&prev);
877 strbuf_reset(&prev);
879 if (!handle_boundary())
880 goto handle_body_out;
883 /* Unwrap transfer encoding */
884 decode_transfer_encoding(&line);
886 switch (transfer_encoding) {
887 case TE_BASE64:
888 case TE_QP:
890 struct strbuf **lines, **it, *sb;
892 /* Prepend any previous partial lines */
893 strbuf_insert(&line, 0, prev.buf, prev.len);
894 strbuf_reset(&prev);
896 /* binary data most likely doesn't have newlines */
897 if (message_type != TYPE_TEXT) {
898 handle_filter(&line);
899 break;
902 * This is a decoded line that may contain
903 * multiple new lines. Pass only one chunk
904 * at a time to handle_filter()
906 lines = strbuf_split(&line, '\n');
907 for (it = lines; (sb = *it); it++) {
908 if (*(it + 1) == NULL) /* The last line */
909 if (sb->buf[sb->len - 1] != '\n') {
910 /* Partial line, save it for later. */
911 strbuf_addbuf(&prev, sb);
912 break;
914 handle_filter(sb);
917 * The partial chunk is saved in "prev" and will be
918 * appended by the next iteration of read_line_with_nul().
920 strbuf_list_free(lines);
921 break;
923 default:
924 handle_filter(&line);
927 } while (!strbuf_getwholeline(&line, fin, '\n'));
929 handle_body_out:
930 strbuf_release(&prev);
933 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
935 const char *sp = data->buf;
936 while (1) {
937 char *ep = strchr(sp, '\n');
938 int len;
939 if (!ep)
940 len = strlen(sp);
941 else
942 len = ep - sp;
943 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
944 if (!ep)
945 break;
946 sp = ep + 1;
950 static void handle_info(void)
952 struct strbuf *hdr;
953 int i;
955 for (i = 0; header[i]; i++) {
956 /* only print inbody headers if we output a patch file */
957 if (patch_lines && s_hdr_data[i])
958 hdr = s_hdr_data[i];
959 else if (p_hdr_data[i])
960 hdr = p_hdr_data[i];
961 else
962 continue;
964 if (!memcmp(header[i], "Subject", 7)) {
965 if (!keep_subject) {
966 cleanup_subject(hdr);
967 cleanup_space(hdr);
969 output_header_lines(fout, "Subject", hdr);
970 } else if (!memcmp(header[i], "From", 4)) {
971 cleanup_space(hdr);
972 handle_from(hdr);
973 fprintf(fout, "Author: %s\n", name.buf);
974 fprintf(fout, "Email: %s\n", email.buf);
975 } else {
976 cleanup_space(hdr);
977 fprintf(fout, "%s: %s\n", header[i], hdr->buf);
980 fprintf(fout, "\n");
983 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
985 int peek;
986 fin = in;
987 fout = out;
989 cmitmsg = fopen(msg, "w");
990 if (!cmitmsg) {
991 perror(msg);
992 return -1;
994 patchfile = fopen(patch, "w");
995 if (!patchfile) {
996 perror(patch);
997 fclose(cmitmsg);
998 return -1;
1001 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
1002 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
1004 do {
1005 peek = fgetc(in);
1006 } while (isspace(peek));
1007 ungetc(peek, in);
1009 /* process the email header */
1010 while (read_one_header_line(&line, fin))
1011 check_header(&line, p_hdr_data, 1);
1013 handle_body();
1014 handle_info();
1016 return 0;
1019 static int git_mailinfo_config(const char *var, const char *value, void *unused)
1021 if (prefixcmp(var, "mailinfo."))
1022 return git_default_config(var, value, unused);
1023 if (!strcmp(var, "mailinfo.scissors")) {
1024 use_scissors = git_config_bool(var, value);
1025 return 0;
1027 /* perhaps others here */
1028 return 0;
1031 static const char mailinfo_usage[] =
1032 "git mailinfo [-k|-b] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] msg patch < mail >info";
1034 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1036 const char *def_charset;
1038 /* NEEDSWORK: might want to do the optional .git/ directory
1039 * discovery
1041 git_config(git_mailinfo_config, NULL);
1043 def_charset = get_commit_output_encoding();
1044 metainfo_charset = def_charset;
1046 while (1 < argc && argv[1][0] == '-') {
1047 if (!strcmp(argv[1], "-k"))
1048 keep_subject = 1;
1049 else if (!strcmp(argv[1], "-b"))
1050 keep_non_patch_brackets_in_subject = 1;
1051 else if (!strcmp(argv[1], "-u"))
1052 metainfo_charset = def_charset;
1053 else if (!strcmp(argv[1], "-n"))
1054 metainfo_charset = NULL;
1055 else if (!prefixcmp(argv[1], "--encoding="))
1056 metainfo_charset = argv[1] + 11;
1057 else if (!strcmp(argv[1], "--scissors"))
1058 use_scissors = 1;
1059 else if (!strcmp(argv[1], "--no-scissors"))
1060 use_scissors = 0;
1061 else if (!strcmp(argv[1], "--no-inbody-headers"))
1062 use_inbody_headers = 0;
1063 else
1064 usage(mailinfo_usage);
1065 argc--; argv++;
1068 if (argc != 3)
1069 usage(mailinfo_usage);
1071 return !!mailinfo(stdin, stdout, argv[1], argv[2]);