mailinfo: don't require "text" mime type for attachments
[git/jnareb-git.git] / builtin / mailinfo.c
blob2405040ad3c03495ad808c06835d8496bf1fba53
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;
23 static struct strbuf charset = STRBUF_INIT;
24 static int patch_lines;
25 static struct strbuf **p_hdr_data, **s_hdr_data;
26 static int use_scissors;
27 static int use_inbody_headers = 1;
29 #define MAX_HDR_PARSED 10
30 #define MAX_BOUNDARIES 5
32 static void cleanup_space(struct strbuf *sb);
35 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
37 struct strbuf *src = name;
38 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
39 strchr(name->buf, '<') || strchr(name->buf, '>'))
40 src = email;
41 else if (name == out)
42 return;
43 strbuf_reset(out);
44 strbuf_addbuf(out, src);
47 static void parse_bogus_from(const struct strbuf *line)
49 /* John Doe <johndoe> */
51 char *bra, *ket;
52 /* This is fallback, so do not bother if we already have an
53 * e-mail address.
55 if (email.len)
56 return;
58 bra = strchr(line->buf, '<');
59 if (!bra)
60 return;
61 ket = strchr(bra, '>');
62 if (!ket)
63 return;
65 strbuf_reset(&email);
66 strbuf_add(&email, bra + 1, ket - bra - 1);
68 strbuf_reset(&name);
69 strbuf_add(&name, line->buf, bra - line->buf);
70 strbuf_trim(&name);
71 get_sane_name(&name, &name, &email);
74 static void handle_from(const struct strbuf *from)
76 char *at;
77 size_t el;
78 struct strbuf f;
80 strbuf_init(&f, from->len);
81 strbuf_addbuf(&f, from);
83 at = strchr(f.buf, '@');
84 if (!at) {
85 parse_bogus_from(from);
86 return;
90 * If we already have one email, don't take any confusing lines
92 if (email.len && strchr(at + 1, '@')) {
93 strbuf_release(&f);
94 return;
97 /* Pick up the string around '@', possibly delimited with <>
98 * pair; that is the email part.
100 while (at > f.buf) {
101 char c = at[-1];
102 if (isspace(c))
103 break;
104 if (c == '<') {
105 at[-1] = ' ';
106 break;
108 at--;
110 el = strcspn(at, " \n\t\r\v\f>");
111 strbuf_reset(&email);
112 strbuf_add(&email, at, el);
113 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
115 /* The remainder is name. It could be
117 * - "John Doe <john.doe@xz>" (a), or
118 * - "john.doe@xz (John Doe)" (b), or
119 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
121 * but we have removed the email part, so
123 * - remove extra spaces which could stay after email (case 'c'), and
124 * - trim from both ends, possibly removing the () pair at the end
125 * (cases 'a' and 'b').
127 cleanup_space(&f);
128 strbuf_trim(&f);
129 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
130 strbuf_remove(&f, 0, 1);
131 strbuf_setlen(&f, f.len - 1);
134 get_sane_name(&name, &f, &email);
135 strbuf_release(&f);
138 static void handle_header(struct strbuf **out, const struct strbuf *line)
140 if (!*out) {
141 *out = xmalloc(sizeof(struct strbuf));
142 strbuf_init(*out, line->len);
143 } else
144 strbuf_reset(*out);
146 strbuf_addbuf(*out, line);
149 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
150 * to have enough heuristics to grok MIME encoded patches often found
151 * on our mailing lists. For example, we do not even treat header lines
152 * case insensitively.
155 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
157 const char *ends, *ap = strcasestr(line, name);
158 size_t sz;
160 if (!ap) {
161 strbuf_setlen(attr, 0);
162 return 0;
164 ap += strlen(name);
165 if (*ap == '"') {
166 ap++;
167 ends = "\"";
169 else
170 ends = "; \t";
171 sz = strcspn(ap, ends);
172 strbuf_add(attr, ap, sz);
173 return 1;
176 static struct strbuf *content[MAX_BOUNDARIES];
178 static struct strbuf **content_top = content;
180 static void handle_content_type(struct strbuf *line)
182 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
183 strbuf_init(boundary, line->len);
185 if (slurp_attr(line->buf, "boundary=", boundary)) {
186 strbuf_insert(boundary, 0, "--", 2);
187 if (++content_top > &content[MAX_BOUNDARIES]) {
188 fprintf(stderr, "Too many boundaries to handle\n");
189 exit(1);
191 *content_top = boundary;
192 boundary = NULL;
194 slurp_attr(line->buf, "charset=", &charset);
196 if (boundary) {
197 strbuf_release(boundary);
198 free(boundary);
202 static void handle_content_transfer_encoding(const struct strbuf *line)
204 if (strcasestr(line->buf, "base64"))
205 transfer_encoding = TE_BASE64;
206 else if (strcasestr(line->buf, "quoted-printable"))
207 transfer_encoding = TE_QP;
208 else
209 transfer_encoding = TE_DONTCARE;
212 static int is_multipart_boundary(const struct strbuf *line)
214 return (((*content_top)->len <= line->len) &&
215 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
218 static void cleanup_subject(struct strbuf *subject)
220 size_t at = 0;
222 while (at < subject->len) {
223 char *pos;
224 size_t remove;
226 switch (subject->buf[at]) {
227 case 'r': case 'R':
228 if (subject->len <= at + 3)
229 break;
230 if (!memcmp(subject->buf + at + 1, "e:", 2)) {
231 strbuf_remove(subject, at, 3);
232 continue;
234 at++;
235 break;
236 case ' ': case '\t': case ':':
237 strbuf_remove(subject, at, 1);
238 continue;
239 case '[':
240 pos = strchr(subject->buf + at, ']');
241 if (!pos)
242 break;
243 remove = pos - subject->buf + at + 1;
244 if (!keep_non_patch_brackets_in_subject ||
245 (7 <= remove &&
246 memmem(subject->buf + at, remove, "PATCH", 5)))
247 strbuf_remove(subject, at, remove);
248 else
249 at += remove;
250 continue;
252 break;
254 strbuf_trim(subject);
257 static void cleanup_space(struct strbuf *sb)
259 size_t pos, cnt;
260 for (pos = 0; pos < sb->len; pos++) {
261 if (isspace(sb->buf[pos])) {
262 sb->buf[pos] = ' ';
263 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
264 strbuf_remove(sb, pos + 1, cnt);
269 static void decode_header(struct strbuf *line);
270 static const char *header[MAX_HDR_PARSED] = {
271 "From","Subject","Date",
274 static inline int cmp_header(const struct strbuf *line, const char *hdr)
276 int len = strlen(hdr);
277 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
278 line->buf[len] == ':' && isspace(line->buf[len + 1]);
281 static int check_header(const struct strbuf *line,
282 struct strbuf *hdr_data[], int overwrite)
284 int i, ret = 0, len;
285 struct strbuf sb = STRBUF_INIT;
286 /* search for the interesting parts */
287 for (i = 0; header[i]; i++) {
288 int len = strlen(header[i]);
289 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
290 /* Unwrap inline B and Q encoding, and optionally
291 * normalize the meta information to utf8.
293 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
294 decode_header(&sb);
295 handle_header(&hdr_data[i], &sb);
296 ret = 1;
297 goto check_header_out;
301 /* Content stuff */
302 if (cmp_header(line, "Content-Type")) {
303 len = strlen("Content-Type: ");
304 strbuf_add(&sb, line->buf + len, line->len - len);
305 decode_header(&sb);
306 strbuf_insert(&sb, 0, "Content-Type: ", len);
307 handle_content_type(&sb);
308 ret = 1;
309 goto check_header_out;
311 if (cmp_header(line, "Content-Transfer-Encoding")) {
312 len = strlen("Content-Transfer-Encoding: ");
313 strbuf_add(&sb, line->buf + len, line->len - len);
314 decode_header(&sb);
315 handle_content_transfer_encoding(&sb);
316 ret = 1;
317 goto check_header_out;
320 /* for inbody stuff */
321 if (!prefixcmp(line->buf, ">From") && isspace(line->buf[5])) {
322 ret = 1; /* Should this return 0? */
323 goto check_header_out;
325 if (!prefixcmp(line->buf, "[PATCH]") && isspace(line->buf[7])) {
326 for (i = 0; header[i]; i++) {
327 if (!memcmp("Subject", header[i], 7)) {
328 handle_header(&hdr_data[i], line);
329 ret = 1;
330 goto check_header_out;
335 check_header_out:
336 strbuf_release(&sb);
337 return ret;
340 static int is_rfc2822_header(const struct strbuf *line)
343 * The section that defines the loosest possible
344 * field name is "3.6.8 Optional fields".
346 * optional-field = field-name ":" unstructured CRLF
347 * field-name = 1*ftext
348 * ftext = %d33-57 / %59-126
350 int ch;
351 char *cp = line->buf;
353 /* Count mbox From headers as headers */
354 if (!prefixcmp(cp, "From ") || !prefixcmp(cp, ">From "))
355 return 1;
357 while ((ch = *cp++)) {
358 if (ch == ':')
359 return 1;
360 if ((33 <= ch && ch <= 57) ||
361 (59 <= ch && ch <= 126))
362 continue;
363 break;
365 return 0;
368 static int read_one_header_line(struct strbuf *line, FILE *in)
370 /* Get the first part of the line. */
371 if (strbuf_getline(line, in, '\n'))
372 return 0;
375 * Is it an empty line or not a valid rfc2822 header?
376 * If so, stop here, and return false ("not a header")
378 strbuf_rtrim(line);
379 if (!line->len || !is_rfc2822_header(line)) {
380 /* Re-add the newline */
381 strbuf_addch(line, '\n');
382 return 0;
386 * Now we need to eat all the continuation lines..
387 * Yuck, 2822 header "folding"
389 for (;;) {
390 int peek;
391 struct strbuf continuation = STRBUF_INIT;
393 peek = fgetc(in); ungetc(peek, in);
394 if (peek != ' ' && peek != '\t')
395 break;
396 if (strbuf_getline(&continuation, in, '\n'))
397 break;
398 continuation.buf[0] = ' ';
399 strbuf_rtrim(&continuation);
400 strbuf_addbuf(line, &continuation);
403 return 1;
406 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
408 const char *in = q_seg->buf;
409 int c;
410 struct strbuf *out = xmalloc(sizeof(struct strbuf));
411 strbuf_init(out, q_seg->len);
413 while ((c = *in++) != 0) {
414 if (c == '=') {
415 int d = *in++;
416 if (d == '\n' || !d)
417 break; /* drop trailing newline */
418 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
419 continue;
421 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
422 c = 0x20;
423 strbuf_addch(out, c);
425 return out;
428 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
430 /* Decode in..ep, possibly in-place to ot */
431 int c, pos = 0, acc = 0;
432 const char *in = b_seg->buf;
433 struct strbuf *out = xmalloc(sizeof(struct strbuf));
434 strbuf_init(out, b_seg->len);
436 while ((c = *in++) != 0) {
437 if (c == '+')
438 c = 62;
439 else if (c == '/')
440 c = 63;
441 else if ('A' <= c && c <= 'Z')
442 c -= 'A';
443 else if ('a' <= c && c <= 'z')
444 c -= 'a' - 26;
445 else if ('0' <= c && c <= '9')
446 c -= '0' - 52;
447 else
448 continue; /* garbage */
449 switch (pos++) {
450 case 0:
451 acc = (c << 2);
452 break;
453 case 1:
454 strbuf_addch(out, (acc | (c >> 4)));
455 acc = (c & 15) << 4;
456 break;
457 case 2:
458 strbuf_addch(out, (acc | (c >> 2)));
459 acc = (c & 3) << 6;
460 break;
461 case 3:
462 strbuf_addch(out, (acc | c));
463 acc = pos = 0;
464 break;
467 return out;
471 * When there is no known charset, guess.
473 * Right now we assume that if the target is UTF-8 (the default),
474 * and it already looks like UTF-8 (which includes US-ASCII as its
475 * subset, of course) then that is what it is and there is nothing
476 * to do.
478 * Otherwise, we default to assuming it is Latin1 for historical
479 * reasons.
481 static const char *guess_charset(const struct strbuf *line, const char *target_charset)
483 if (is_encoding_utf8(target_charset)) {
484 if (is_utf8(line->buf))
485 return NULL;
487 return "ISO8859-1";
490 static void convert_to_utf8(struct strbuf *line, const char *charset)
492 char *out;
494 if (!charset || !*charset) {
495 charset = guess_charset(line, metainfo_charset);
496 if (!charset)
497 return;
500 if (!strcasecmp(metainfo_charset, charset))
501 return;
502 out = reencode_string(line->buf, metainfo_charset, charset);
503 if (!out)
504 die("cannot convert from %s to %s",
505 charset, metainfo_charset);
506 strbuf_attach(line, out, strlen(out), strlen(out));
509 static int decode_header_bq(struct strbuf *it)
511 char *in, *ep, *cp;
512 struct strbuf outbuf = STRBUF_INIT, *dec;
513 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
514 int rfc2047 = 0;
516 in = it->buf;
517 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
518 int encoding;
519 strbuf_reset(&charset_q);
520 strbuf_reset(&piecebuf);
521 rfc2047 = 1;
523 if (in != ep) {
525 * We are about to process an encoded-word
526 * that begins at ep, but there is something
527 * before the encoded word.
529 char *scan;
530 for (scan = in; scan < ep; scan++)
531 if (!isspace(*scan))
532 break;
534 if (scan != ep || in == it->buf) {
536 * We should not lose that "something",
537 * unless we have just processed an
538 * encoded-word, and there is only LWS
539 * before the one we are about to process.
541 strbuf_add(&outbuf, in, ep - in);
544 /* E.g.
545 * ep : "=?iso-2022-jp?B?GyR...?= foo"
546 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
548 ep += 2;
550 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
551 goto decode_header_bq_out;
553 if (cp + 3 - it->buf > it->len)
554 goto decode_header_bq_out;
555 strbuf_add(&charset_q, ep, cp - ep);
557 encoding = cp[1];
558 if (!encoding || cp[2] != '?')
559 goto decode_header_bq_out;
560 ep = strstr(cp + 3, "?=");
561 if (!ep)
562 goto decode_header_bq_out;
563 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
564 switch (tolower(encoding)) {
565 default:
566 goto decode_header_bq_out;
567 case 'b':
568 dec = decode_b_segment(&piecebuf);
569 break;
570 case 'q':
571 dec = decode_q_segment(&piecebuf, 1);
572 break;
574 if (metainfo_charset)
575 convert_to_utf8(dec, charset_q.buf);
577 strbuf_addbuf(&outbuf, dec);
578 strbuf_release(dec);
579 free(dec);
580 in = ep + 2;
582 strbuf_addstr(&outbuf, in);
583 strbuf_reset(it);
584 strbuf_addbuf(it, &outbuf);
585 decode_header_bq_out:
586 strbuf_release(&outbuf);
587 strbuf_release(&charset_q);
588 strbuf_release(&piecebuf);
589 return rfc2047;
592 static void decode_header(struct strbuf *it)
594 if (decode_header_bq(it))
595 return;
596 /* otherwise "it" is a straight copy of the input.
597 * This can be binary guck but there is no charset specified.
599 if (metainfo_charset)
600 convert_to_utf8(it, "");
603 static void decode_transfer_encoding(struct strbuf *line)
605 struct strbuf *ret;
607 switch (transfer_encoding) {
608 case TE_QP:
609 ret = decode_q_segment(line, 0);
610 break;
611 case TE_BASE64:
612 ret = decode_b_segment(line);
613 break;
614 case TE_DONTCARE:
615 default:
616 return;
618 strbuf_reset(line);
619 strbuf_addbuf(line, ret);
620 strbuf_release(ret);
621 free(ret);
624 static void handle_filter(struct strbuf *line);
626 static int find_boundary(void)
628 while (!strbuf_getline(&line, fin, '\n')) {
629 if (*content_top && is_multipart_boundary(&line))
630 return 1;
632 return 0;
635 static int handle_boundary(void)
637 struct strbuf newline = STRBUF_INIT;
639 strbuf_addch(&newline, '\n');
640 again:
641 if (line.len >= (*content_top)->len + 2 &&
642 !memcmp(line.buf + (*content_top)->len, "--", 2)) {
643 /* we hit an end boundary */
644 /* pop the current boundary off the stack */
645 strbuf_release(*content_top);
646 free(*content_top);
647 *content_top = NULL;
649 /* technically won't happen as is_multipart_boundary()
650 will fail first. But just in case..
652 if (--content_top < content) {
653 fprintf(stderr, "Detected mismatched boundaries, "
654 "can't recover\n");
655 exit(1);
657 handle_filter(&newline);
658 strbuf_release(&newline);
660 /* skip to the next boundary */
661 if (!find_boundary())
662 return 0;
663 goto again;
666 /* set some defaults */
667 transfer_encoding = TE_DONTCARE;
668 strbuf_reset(&charset);
670 /* slurp in this section's info */
671 while (read_one_header_line(&line, fin))
672 check_header(&line, p_hdr_data, 0);
674 strbuf_release(&newline);
675 /* replenish line */
676 if (strbuf_getline(&line, fin, '\n'))
677 return 0;
678 strbuf_addch(&line, '\n');
679 return 1;
682 static inline int patchbreak(const struct strbuf *line)
684 size_t i;
686 /* Beginning of a "diff -" header? */
687 if (!prefixcmp(line->buf, "diff -"))
688 return 1;
690 /* CVS "Index: " line? */
691 if (!prefixcmp(line->buf, "Index: "))
692 return 1;
695 * "--- <filename>" starts patches without headers
696 * "---<sp>*" is a manual separator
698 if (line->len < 4)
699 return 0;
701 if (!prefixcmp(line->buf, "---")) {
702 /* space followed by a filename? */
703 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
704 return 1;
705 /* Just whitespace? */
706 for (i = 3; i < line->len; i++) {
707 unsigned char c = line->buf[i];
708 if (c == '\n')
709 return 1;
710 if (!isspace(c))
711 break;
713 return 0;
715 return 0;
718 static int is_scissors_line(const struct strbuf *line)
720 size_t i, len = line->len;
721 int scissors = 0, gap = 0;
722 int first_nonblank = -1;
723 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
724 const char *buf = line->buf;
726 for (i = 0; i < len; i++) {
727 if (isspace(buf[i])) {
728 if (in_perforation) {
729 perforation++;
730 gap++;
732 continue;
734 last_nonblank = i;
735 if (first_nonblank < 0)
736 first_nonblank = i;
737 if (buf[i] == '-') {
738 in_perforation = 1;
739 perforation++;
740 continue;
742 if (i + 1 < len &&
743 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
744 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
745 in_perforation = 1;
746 perforation += 2;
747 scissors += 2;
748 i++;
749 continue;
751 in_perforation = 0;
755 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
756 * Even though there can be arbitrary cruft on the same line
757 * (e.g. "cut here"), in order to avoid misidentification, the
758 * perforation must occupy more than a third of the visible
759 * width of the line, and dashes and scissors must occupy more
760 * than half of the perforation.
763 visible = last_nonblank - first_nonblank + 1;
764 return (scissors && 8 <= visible &&
765 visible < perforation * 3 &&
766 gap * 2 < perforation);
769 static int handle_commit_msg(struct strbuf *line)
771 static int still_looking = 1;
773 if (!cmitmsg)
774 return 0;
776 if (still_looking) {
777 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
778 return 0;
781 if (use_inbody_headers && still_looking) {
782 still_looking = check_header(line, s_hdr_data, 0);
783 if (still_looking)
784 return 0;
785 } else
786 /* Only trim the first (blank) line of the commit message
787 * when ignoring in-body headers.
789 still_looking = 0;
791 /* normalize the log message to UTF-8. */
792 if (metainfo_charset)
793 convert_to_utf8(line, charset.buf);
795 if (use_scissors && is_scissors_line(line)) {
796 int i;
797 if (fseek(cmitmsg, 0L, SEEK_SET))
798 die_errno("Could not rewind output message file");
799 if (ftruncate(fileno(cmitmsg), 0))
800 die_errno("Could not truncate output message file at scissors");
801 still_looking = 1;
804 * We may have already read "secondary headers"; purge
805 * them to give ourselves a clean restart.
807 for (i = 0; header[i]; i++) {
808 if (s_hdr_data[i])
809 strbuf_release(s_hdr_data[i]);
810 s_hdr_data[i] = NULL;
812 return 0;
815 if (patchbreak(line)) {
816 fclose(cmitmsg);
817 cmitmsg = NULL;
818 return 1;
821 fputs(line->buf, cmitmsg);
822 return 0;
825 static void handle_patch(const struct strbuf *line)
827 fwrite(line->buf, 1, line->len, patchfile);
828 patch_lines++;
831 static void handle_filter(struct strbuf *line)
833 static int filter = 0;
835 /* filter tells us which part we left off on */
836 switch (filter) {
837 case 0:
838 if (!handle_commit_msg(line))
839 break;
840 filter++;
841 case 1:
842 handle_patch(line);
843 break;
847 static void handle_body(void)
849 struct strbuf prev = STRBUF_INIT;
851 /* Skip up to the first boundary */
852 if (*content_top) {
853 if (!find_boundary())
854 goto handle_body_out;
857 do {
858 /* process any boundary lines */
859 if (*content_top && is_multipart_boundary(&line)) {
860 /* flush any leftover */
861 if (prev.len) {
862 handle_filter(&prev);
863 strbuf_reset(&prev);
865 if (!handle_boundary())
866 goto handle_body_out;
869 /* Unwrap transfer encoding */
870 decode_transfer_encoding(&line);
872 switch (transfer_encoding) {
873 case TE_BASE64:
874 case TE_QP:
876 struct strbuf **lines, **it, *sb;
878 /* Prepend any previous partial lines */
879 strbuf_insert(&line, 0, prev.buf, prev.len);
880 strbuf_reset(&prev);
883 * This is a decoded line that may contain
884 * multiple new lines. Pass only one chunk
885 * at a time to handle_filter()
887 lines = strbuf_split(&line, '\n');
888 for (it = lines; (sb = *it); it++) {
889 if (*(it + 1) == NULL) /* The last line */
890 if (sb->buf[sb->len - 1] != '\n') {
891 /* Partial line, save it for later. */
892 strbuf_addbuf(&prev, sb);
893 break;
895 handle_filter(sb);
898 * The partial chunk is saved in "prev" and will be
899 * appended by the next iteration of read_line_with_nul().
901 strbuf_list_free(lines);
902 break;
904 default:
905 handle_filter(&line);
908 } while (!strbuf_getwholeline(&line, fin, '\n'));
910 handle_body_out:
911 strbuf_release(&prev);
914 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
916 const char *sp = data->buf;
917 while (1) {
918 char *ep = strchr(sp, '\n');
919 int len;
920 if (!ep)
921 len = strlen(sp);
922 else
923 len = ep - sp;
924 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
925 if (!ep)
926 break;
927 sp = ep + 1;
931 static void handle_info(void)
933 struct strbuf *hdr;
934 int i;
936 for (i = 0; header[i]; i++) {
937 /* only print inbody headers if we output a patch file */
938 if (patch_lines && s_hdr_data[i])
939 hdr = s_hdr_data[i];
940 else if (p_hdr_data[i])
941 hdr = p_hdr_data[i];
942 else
943 continue;
945 if (!memcmp(header[i], "Subject", 7)) {
946 if (!keep_subject) {
947 cleanup_subject(hdr);
948 cleanup_space(hdr);
950 output_header_lines(fout, "Subject", hdr);
951 } else if (!memcmp(header[i], "From", 4)) {
952 cleanup_space(hdr);
953 handle_from(hdr);
954 fprintf(fout, "Author: %s\n", name.buf);
955 fprintf(fout, "Email: %s\n", email.buf);
956 } else {
957 cleanup_space(hdr);
958 fprintf(fout, "%s: %s\n", header[i], hdr->buf);
961 fprintf(fout, "\n");
964 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
966 int peek;
967 fin = in;
968 fout = out;
970 cmitmsg = fopen(msg, "w");
971 if (!cmitmsg) {
972 perror(msg);
973 return -1;
975 patchfile = fopen(patch, "w");
976 if (!patchfile) {
977 perror(patch);
978 fclose(cmitmsg);
979 return -1;
982 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
983 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
985 do {
986 peek = fgetc(in);
987 } while (isspace(peek));
988 ungetc(peek, in);
990 /* process the email header */
991 while (read_one_header_line(&line, fin))
992 check_header(&line, p_hdr_data, 1);
994 handle_body();
995 handle_info();
997 return 0;
1000 static int git_mailinfo_config(const char *var, const char *value, void *unused)
1002 if (prefixcmp(var, "mailinfo."))
1003 return git_default_config(var, value, unused);
1004 if (!strcmp(var, "mailinfo.scissors")) {
1005 use_scissors = git_config_bool(var, value);
1006 return 0;
1008 /* perhaps others here */
1009 return 0;
1012 static const char mailinfo_usage[] =
1013 "git mailinfo [-k|-b] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] msg patch < mail >info";
1015 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1017 const char *def_charset;
1019 /* NEEDSWORK: might want to do the optional .git/ directory
1020 * discovery
1022 git_config(git_mailinfo_config, NULL);
1024 def_charset = get_commit_output_encoding();
1025 metainfo_charset = def_charset;
1027 while (1 < argc && argv[1][0] == '-') {
1028 if (!strcmp(argv[1], "-k"))
1029 keep_subject = 1;
1030 else if (!strcmp(argv[1], "-b"))
1031 keep_non_patch_brackets_in_subject = 1;
1032 else if (!strcmp(argv[1], "-u"))
1033 metainfo_charset = def_charset;
1034 else if (!strcmp(argv[1], "-n"))
1035 metainfo_charset = NULL;
1036 else if (!prefixcmp(argv[1], "--encoding="))
1037 metainfo_charset = argv[1] + 11;
1038 else if (!strcmp(argv[1], "--scissors"))
1039 use_scissors = 1;
1040 else if (!strcmp(argv[1], "--no-scissors"))
1041 use_scissors = 0;
1042 else if (!strcmp(argv[1], "--no-inbody-headers"))
1043 use_inbody_headers = 0;
1044 else
1045 usage(mailinfo_usage);
1046 argc--; argv++;
1049 if (argc != 3)
1050 usage(mailinfo_usage);
1052 return !!mailinfo(stdin, stdout, argv[1], argv[2]);