mailinfo: move read_one_header_line() closer to its callers
[alt-git.git] / builtin / mailinfo.c
blob04927f7ae590a305da356c98bc7aa75c2a3deabe
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;
18 static char *message_id;
20 static enum {
21 TE_DONTCARE, TE_QP, TE_BASE64
22 } transfer_encoding;
24 static struct strbuf charset = STRBUF_INIT;
25 static int patch_lines;
26 static struct strbuf **p_hdr_data, **s_hdr_data;
27 static int use_scissors;
28 static int add_message_id;
29 static int use_inbody_headers = 1;
31 #define MAX_HDR_PARSED 10
32 #define MAX_BOUNDARIES 5
34 static void cleanup_space(struct strbuf *sb);
37 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
39 struct strbuf *src = name;
40 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
41 strchr(name->buf, '<') || strchr(name->buf, '>'))
42 src = email;
43 else if (name == out)
44 return;
45 strbuf_reset(out);
46 strbuf_addbuf(out, src);
49 static void parse_bogus_from(const struct strbuf *line)
51 /* John Doe <johndoe> */
53 char *bra, *ket;
54 /* This is fallback, so do not bother if we already have an
55 * e-mail address.
57 if (email.len)
58 return;
60 bra = strchr(line->buf, '<');
61 if (!bra)
62 return;
63 ket = strchr(bra, '>');
64 if (!ket)
65 return;
67 strbuf_reset(&email);
68 strbuf_add(&email, bra + 1, ket - bra - 1);
70 strbuf_reset(&name);
71 strbuf_add(&name, line->buf, bra - line->buf);
72 strbuf_trim(&name);
73 get_sane_name(&name, &name, &email);
76 static void handle_from(const struct strbuf *from)
78 char *at;
79 size_t el;
80 struct strbuf f;
82 strbuf_init(&f, from->len);
83 strbuf_addbuf(&f, from);
85 at = strchr(f.buf, '@');
86 if (!at) {
87 parse_bogus_from(from);
88 return;
92 * If we already have one email, don't take any confusing lines
94 if (email.len && strchr(at + 1, '@')) {
95 strbuf_release(&f);
96 return;
99 /* Pick up the string around '@', possibly delimited with <>
100 * pair; that is the email part.
102 while (at > f.buf) {
103 char c = at[-1];
104 if (isspace(c))
105 break;
106 if (c == '<') {
107 at[-1] = ' ';
108 break;
110 at--;
112 el = strcspn(at, " \n\t\r\v\f>");
113 strbuf_reset(&email);
114 strbuf_add(&email, at, el);
115 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
117 /* The remainder is name. It could be
119 * - "John Doe <john.doe@xz>" (a), or
120 * - "john.doe@xz (John Doe)" (b), or
121 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
123 * but we have removed the email part, so
125 * - remove extra spaces which could stay after email (case 'c'), and
126 * - trim from both ends, possibly removing the () pair at the end
127 * (cases 'a' and 'b').
129 cleanup_space(&f);
130 strbuf_trim(&f);
131 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
132 strbuf_remove(&f, 0, 1);
133 strbuf_setlen(&f, f.len - 1);
136 get_sane_name(&name, &f, &email);
137 strbuf_release(&f);
140 static void handle_header(struct strbuf **out, const struct strbuf *line)
142 if (!*out) {
143 *out = xmalloc(sizeof(struct strbuf));
144 strbuf_init(*out, line->len);
145 } else
146 strbuf_reset(*out);
148 strbuf_addbuf(*out, line);
151 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
152 * to have enough heuristics to grok MIME encoded patches often found
153 * on our mailing lists. For example, we do not even treat header lines
154 * case insensitively.
157 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
159 const char *ends, *ap = strcasestr(line, name);
160 size_t sz;
162 strbuf_setlen(attr, 0);
163 if (!ap)
164 return 0;
165 ap += strlen(name);
166 if (*ap == '"') {
167 ap++;
168 ends = "\"";
170 else
171 ends = "; \t";
172 sz = strcspn(ap, ends);
173 strbuf_add(attr, ap, sz);
174 return 1;
177 static struct strbuf *content[MAX_BOUNDARIES];
179 static struct strbuf **content_top = content;
181 static void handle_content_type(struct strbuf *line)
183 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
184 strbuf_init(boundary, line->len);
186 if (slurp_attr(line->buf, "boundary=", boundary)) {
187 strbuf_insert(boundary, 0, "--", 2);
188 if (++content_top >= &content[MAX_BOUNDARIES]) {
189 fprintf(stderr, "Too many boundaries to handle\n");
190 exit(1);
192 *content_top = boundary;
193 boundary = NULL;
195 slurp_attr(line->buf, "charset=", &charset);
197 if (boundary) {
198 strbuf_release(boundary);
199 free(boundary);
203 static void handle_message_id(const struct strbuf *line)
205 if (add_message_id)
206 message_id = strdup(line->buf);
209 static void handle_content_transfer_encoding(const struct strbuf *line)
211 if (strcasestr(line->buf, "base64"))
212 transfer_encoding = TE_BASE64;
213 else if (strcasestr(line->buf, "quoted-printable"))
214 transfer_encoding = TE_QP;
215 else
216 transfer_encoding = TE_DONTCARE;
219 static int is_multipart_boundary(const struct strbuf *line)
221 return (((*content_top)->len <= line->len) &&
222 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
225 static void cleanup_subject(struct strbuf *subject)
227 size_t at = 0;
229 while (at < subject->len) {
230 char *pos;
231 size_t remove;
233 switch (subject->buf[at]) {
234 case 'r': case 'R':
235 if (subject->len <= at + 3)
236 break;
237 if ((subject->buf[at + 1] == 'e' ||
238 subject->buf[at + 1] == 'E') &&
239 subject->buf[at + 2] == ':') {
240 strbuf_remove(subject, at, 3);
241 continue;
243 at++;
244 break;
245 case ' ': case '\t': case ':':
246 strbuf_remove(subject, at, 1);
247 continue;
248 case '[':
249 pos = strchr(subject->buf + at, ']');
250 if (!pos)
251 break;
252 remove = pos - subject->buf + at + 1;
253 if (!keep_non_patch_brackets_in_subject ||
254 (7 <= remove &&
255 memmem(subject->buf + at, remove, "PATCH", 5)))
256 strbuf_remove(subject, at, remove);
257 else {
258 at += remove;
260 * If the input had a space after the ], keep
261 * it. We don't bother with finding the end of
262 * the space, since we later normalize it
263 * anyway.
265 if (isspace(subject->buf[at]))
266 at += 1;
268 continue;
270 break;
272 strbuf_trim(subject);
275 static void cleanup_space(struct strbuf *sb)
277 size_t pos, cnt;
278 for (pos = 0; pos < sb->len; pos++) {
279 if (isspace(sb->buf[pos])) {
280 sb->buf[pos] = ' ';
281 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
282 strbuf_remove(sb, pos + 1, cnt);
287 static void decode_header(struct strbuf *line);
288 static const char *header[MAX_HDR_PARSED] = {
289 "From","Subject","Date",
292 static inline int cmp_header(const struct strbuf *line, const char *hdr)
294 int len = strlen(hdr);
295 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
296 line->buf[len] == ':' && isspace(line->buf[len + 1]);
299 static int is_format_patch_separator(const char *line, int len)
301 static const char SAMPLE[] =
302 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
303 const char *cp;
305 if (len != strlen(SAMPLE))
306 return 0;
307 if (!skip_prefix(line, "From ", &cp))
308 return 0;
309 if (strspn(cp, "0123456789abcdef") != 40)
310 return 0;
311 cp += 40;
312 return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
315 static int check_header(const struct strbuf *line,
316 struct strbuf *hdr_data[], int overwrite)
318 int i, ret = 0, len;
319 struct strbuf sb = STRBUF_INIT;
320 /* search for the interesting parts */
321 for (i = 0; header[i]; i++) {
322 int len = strlen(header[i]);
323 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
324 /* Unwrap inline B and Q encoding, and optionally
325 * normalize the meta information to utf8.
327 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
328 decode_header(&sb);
329 handle_header(&hdr_data[i], &sb);
330 ret = 1;
331 goto check_header_out;
335 /* Content stuff */
336 if (cmp_header(line, "Content-Type")) {
337 len = strlen("Content-Type: ");
338 strbuf_add(&sb, line->buf + len, line->len - len);
339 decode_header(&sb);
340 strbuf_insert(&sb, 0, "Content-Type: ", len);
341 handle_content_type(&sb);
342 ret = 1;
343 goto check_header_out;
345 if (cmp_header(line, "Content-Transfer-Encoding")) {
346 len = strlen("Content-Transfer-Encoding: ");
347 strbuf_add(&sb, line->buf + len, line->len - len);
348 decode_header(&sb);
349 handle_content_transfer_encoding(&sb);
350 ret = 1;
351 goto check_header_out;
353 if (cmp_header(line, "Message-Id")) {
354 len = strlen("Message-Id: ");
355 strbuf_add(&sb, line->buf + len, line->len - len);
356 decode_header(&sb);
357 handle_message_id(&sb);
358 ret = 1;
359 goto check_header_out;
362 /* for inbody stuff */
363 if (starts_with(line->buf, ">From") && isspace(line->buf[5])) {
364 ret = is_format_patch_separator(line->buf + 1, line->len - 1);
365 goto check_header_out;
367 if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
368 for (i = 0; header[i]; i++) {
369 if (!strcmp("Subject", header[i])) {
370 handle_header(&hdr_data[i], line);
371 ret = 1;
372 goto check_header_out;
377 check_header_out:
378 strbuf_release(&sb);
379 return ret;
382 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
384 const char *in = q_seg->buf;
385 int c;
386 struct strbuf *out = xmalloc(sizeof(struct strbuf));
387 strbuf_init(out, q_seg->len);
389 while ((c = *in++) != 0) {
390 if (c == '=') {
391 int d = *in++;
392 if (d == '\n' || !d)
393 break; /* drop trailing newline */
394 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
395 continue;
397 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
398 c = 0x20;
399 strbuf_addch(out, c);
401 return out;
404 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
406 /* Decode in..ep, possibly in-place to ot */
407 int c, pos = 0, acc = 0;
408 const char *in = b_seg->buf;
409 struct strbuf *out = xmalloc(sizeof(struct strbuf));
410 strbuf_init(out, b_seg->len);
412 while ((c = *in++) != 0) {
413 if (c == '+')
414 c = 62;
415 else if (c == '/')
416 c = 63;
417 else if ('A' <= c && c <= 'Z')
418 c -= 'A';
419 else if ('a' <= c && c <= 'z')
420 c -= 'a' - 26;
421 else if ('0' <= c && c <= '9')
422 c -= '0' - 52;
423 else
424 continue; /* garbage */
425 switch (pos++) {
426 case 0:
427 acc = (c << 2);
428 break;
429 case 1:
430 strbuf_addch(out, (acc | (c >> 4)));
431 acc = (c & 15) << 4;
432 break;
433 case 2:
434 strbuf_addch(out, (acc | (c >> 2)));
435 acc = (c & 3) << 6;
436 break;
437 case 3:
438 strbuf_addch(out, (acc | c));
439 acc = pos = 0;
440 break;
443 return out;
446 static void convert_to_utf8(struct strbuf *line, const char *charset)
448 char *out;
450 if (!charset || !*charset)
451 return;
453 if (same_encoding(metainfo_charset, charset))
454 return;
455 out = reencode_string(line->buf, metainfo_charset, charset);
456 if (!out)
457 die("cannot convert from %s to %s",
458 charset, metainfo_charset);
459 strbuf_attach(line, out, strlen(out), strlen(out));
462 static void decode_header(struct strbuf *it)
464 char *in, *ep, *cp;
465 struct strbuf outbuf = STRBUF_INIT, *dec;
466 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
468 in = it->buf;
469 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
470 int encoding;
471 strbuf_reset(&charset_q);
472 strbuf_reset(&piecebuf);
474 if (in != ep) {
476 * We are about to process an encoded-word
477 * that begins at ep, but there is something
478 * before the encoded word.
480 char *scan;
481 for (scan = in; scan < ep; scan++)
482 if (!isspace(*scan))
483 break;
485 if (scan != ep || in == it->buf) {
487 * We should not lose that "something",
488 * unless we have just processed an
489 * encoded-word, and there is only LWS
490 * before the one we are about to process.
492 strbuf_add(&outbuf, in, ep - in);
495 /* E.g.
496 * ep : "=?iso-2022-jp?B?GyR...?= foo"
497 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
499 ep += 2;
501 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
502 goto release_return;
504 if (cp + 3 - it->buf > it->len)
505 goto release_return;
506 strbuf_add(&charset_q, ep, cp - ep);
508 encoding = cp[1];
509 if (!encoding || cp[2] != '?')
510 goto release_return;
511 ep = strstr(cp + 3, "?=");
512 if (!ep)
513 goto release_return;
514 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
515 switch (tolower(encoding)) {
516 default:
517 goto release_return;
518 case 'b':
519 dec = decode_b_segment(&piecebuf);
520 break;
521 case 'q':
522 dec = decode_q_segment(&piecebuf, 1);
523 break;
525 if (metainfo_charset)
526 convert_to_utf8(dec, charset_q.buf);
528 strbuf_addbuf(&outbuf, dec);
529 strbuf_release(dec);
530 free(dec);
531 in = ep + 2;
533 strbuf_addstr(&outbuf, in);
534 strbuf_reset(it);
535 strbuf_addbuf(it, &outbuf);
536 release_return:
537 strbuf_release(&outbuf);
538 strbuf_release(&charset_q);
539 strbuf_release(&piecebuf);
542 static void decode_transfer_encoding(struct strbuf *line)
544 struct strbuf *ret;
546 switch (transfer_encoding) {
547 case TE_QP:
548 ret = decode_q_segment(line, 0);
549 break;
550 case TE_BASE64:
551 ret = decode_b_segment(line);
552 break;
553 case TE_DONTCARE:
554 default:
555 return;
557 strbuf_reset(line);
558 strbuf_addbuf(line, ret);
559 strbuf_release(ret);
560 free(ret);
563 static inline int patchbreak(const struct strbuf *line)
565 size_t i;
567 /* Beginning of a "diff -" header? */
568 if (starts_with(line->buf, "diff -"))
569 return 1;
571 /* CVS "Index: " line? */
572 if (starts_with(line->buf, "Index: "))
573 return 1;
576 * "--- <filename>" starts patches without headers
577 * "---<sp>*" is a manual separator
579 if (line->len < 4)
580 return 0;
582 if (starts_with(line->buf, "---")) {
583 /* space followed by a filename? */
584 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
585 return 1;
586 /* Just whitespace? */
587 for (i = 3; i < line->len; i++) {
588 unsigned char c = line->buf[i];
589 if (c == '\n')
590 return 1;
591 if (!isspace(c))
592 break;
594 return 0;
596 return 0;
599 static int is_scissors_line(const struct strbuf *line)
601 size_t i, len = line->len;
602 int scissors = 0, gap = 0;
603 int first_nonblank = -1;
604 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
605 const char *buf = line->buf;
607 for (i = 0; i < len; i++) {
608 if (isspace(buf[i])) {
609 if (in_perforation) {
610 perforation++;
611 gap++;
613 continue;
615 last_nonblank = i;
616 if (first_nonblank < 0)
617 first_nonblank = i;
618 if (buf[i] == '-') {
619 in_perforation = 1;
620 perforation++;
621 continue;
623 if (i + 1 < len &&
624 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
625 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
626 in_perforation = 1;
627 perforation += 2;
628 scissors += 2;
629 i++;
630 continue;
632 in_perforation = 0;
636 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
637 * Even though there can be arbitrary cruft on the same line
638 * (e.g. "cut here"), in order to avoid misidentification, the
639 * perforation must occupy more than a third of the visible
640 * width of the line, and dashes and scissors must occupy more
641 * than half of the perforation.
644 visible = last_nonblank - first_nonblank + 1;
645 return (scissors && 8 <= visible &&
646 visible < perforation * 3 &&
647 gap * 2 < perforation);
650 static int handle_commit_msg(struct strbuf *line)
652 static int still_looking = 1;
654 if (!cmitmsg)
655 return 0;
657 if (still_looking) {
658 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
659 return 0;
662 if (use_inbody_headers && still_looking) {
663 still_looking = check_header(line, s_hdr_data, 0);
664 if (still_looking)
665 return 0;
666 } else
667 /* Only trim the first (blank) line of the commit message
668 * when ignoring in-body headers.
670 still_looking = 0;
672 /* normalize the log message to UTF-8. */
673 if (metainfo_charset)
674 convert_to_utf8(line, charset.buf);
676 if (use_scissors && is_scissors_line(line)) {
677 int i;
678 if (fseek(cmitmsg, 0L, SEEK_SET))
679 die_errno("Could not rewind output message file");
680 if (ftruncate(fileno(cmitmsg), 0))
681 die_errno("Could not truncate output message file at scissors");
682 still_looking = 1;
685 * We may have already read "secondary headers"; purge
686 * them to give ourselves a clean restart.
688 for (i = 0; header[i]; i++) {
689 if (s_hdr_data[i])
690 strbuf_release(s_hdr_data[i]);
691 s_hdr_data[i] = NULL;
693 return 0;
696 if (patchbreak(line)) {
697 if (message_id)
698 fprintf(cmitmsg, "Message-Id: %s\n", message_id);
699 fclose(cmitmsg);
700 cmitmsg = NULL;
701 return 1;
704 fputs(line->buf, cmitmsg);
705 return 0;
708 static void handle_patch(const struct strbuf *line)
710 fwrite(line->buf, 1, line->len, patchfile);
711 patch_lines++;
714 static void handle_filter(struct strbuf *line)
716 static int filter = 0;
718 /* filter tells us which part we left off on */
719 switch (filter) {
720 case 0:
721 if (!handle_commit_msg(line))
722 break;
723 filter++;
724 case 1:
725 handle_patch(line);
726 break;
730 static int is_rfc2822_header(const struct strbuf *line)
733 * The section that defines the loosest possible
734 * field name is "3.6.8 Optional fields".
736 * optional-field = field-name ":" unstructured CRLF
737 * field-name = 1*ftext
738 * ftext = %d33-57 / %59-126
740 int ch;
741 char *cp = line->buf;
743 /* Count mbox From headers as headers */
744 if (starts_with(cp, "From ") || starts_with(cp, ">From "))
745 return 1;
747 while ((ch = *cp++)) {
748 if (ch == ':')
749 return 1;
750 if ((33 <= ch && ch <= 57) ||
751 (59 <= ch && ch <= 126))
752 continue;
753 break;
755 return 0;
758 static int read_one_header_line(struct strbuf *line, FILE *in)
760 struct strbuf continuation = STRBUF_INIT;
762 /* Get the first part of the line. */
763 if (strbuf_getline(line, in, '\n'))
764 return 0;
767 * Is it an empty line or not a valid rfc2822 header?
768 * If so, stop here, and return false ("not a header")
770 strbuf_rtrim(line);
771 if (!line->len || !is_rfc2822_header(line)) {
772 /* Re-add the newline */
773 strbuf_addch(line, '\n');
774 return 0;
778 * Now we need to eat all the continuation lines..
779 * Yuck, 2822 header "folding"
781 for (;;) {
782 int peek;
784 peek = fgetc(in); ungetc(peek, in);
785 if (peek != ' ' && peek != '\t')
786 break;
787 if (strbuf_getline(&continuation, in, '\n'))
788 break;
789 continuation.buf[0] = ' ';
790 strbuf_rtrim(&continuation);
791 strbuf_addbuf(line, &continuation);
793 strbuf_release(&continuation);
795 return 1;
798 static int find_boundary(void)
800 while (!strbuf_getline(&line, fin, '\n')) {
801 if (*content_top && is_multipart_boundary(&line))
802 return 1;
804 return 0;
807 static int handle_boundary(void)
809 struct strbuf newline = STRBUF_INIT;
811 strbuf_addch(&newline, '\n');
812 again:
813 if (line.len >= (*content_top)->len + 2 &&
814 !memcmp(line.buf + (*content_top)->len, "--", 2)) {
815 /* we hit an end boundary */
816 /* pop the current boundary off the stack */
817 strbuf_release(*content_top);
818 free(*content_top);
819 *content_top = NULL;
821 /* technically won't happen as is_multipart_boundary()
822 will fail first. But just in case..
824 if (--content_top < content) {
825 fprintf(stderr, "Detected mismatched boundaries, "
826 "can't recover\n");
827 exit(1);
829 handle_filter(&newline);
830 strbuf_release(&newline);
832 /* skip to the next boundary */
833 if (!find_boundary())
834 return 0;
835 goto again;
838 /* set some defaults */
839 transfer_encoding = TE_DONTCARE;
840 strbuf_reset(&charset);
842 /* slurp in this section's info */
843 while (read_one_header_line(&line, fin))
844 check_header(&line, p_hdr_data, 0);
846 strbuf_release(&newline);
847 /* replenish line */
848 if (strbuf_getline(&line, fin, '\n'))
849 return 0;
850 strbuf_addch(&line, '\n');
851 return 1;
854 static void handle_body(void)
856 struct strbuf prev = STRBUF_INIT;
858 /* Skip up to the first boundary */
859 if (*content_top) {
860 if (!find_boundary())
861 goto handle_body_out;
864 do {
865 /* process any boundary lines */
866 if (*content_top && is_multipart_boundary(&line)) {
867 /* flush any leftover */
868 if (prev.len) {
869 handle_filter(&prev);
870 strbuf_reset(&prev);
872 if (!handle_boundary())
873 goto handle_body_out;
876 /* Unwrap transfer encoding */
877 decode_transfer_encoding(&line);
879 switch (transfer_encoding) {
880 case TE_BASE64:
881 case TE_QP:
883 struct strbuf **lines, **it, *sb;
885 /* Prepend any previous partial lines */
886 strbuf_insert(&line, 0, prev.buf, prev.len);
887 strbuf_reset(&prev);
890 * This is a decoded line that may contain
891 * multiple new lines. Pass only one chunk
892 * at a time to handle_filter()
894 lines = strbuf_split(&line, '\n');
895 for (it = lines; (sb = *it); it++) {
896 if (*(it + 1) == NULL) /* The last line */
897 if (sb->buf[sb->len - 1] != '\n') {
898 /* Partial line, save it for later. */
899 strbuf_addbuf(&prev, sb);
900 break;
902 handle_filter(sb);
905 * The partial chunk is saved in "prev" and will be
906 * appended by the next iteration of read_line_with_nul().
908 strbuf_list_free(lines);
909 break;
911 default:
912 handle_filter(&line);
915 } while (!strbuf_getwholeline(&line, fin, '\n'));
917 handle_body_out:
918 strbuf_release(&prev);
921 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
923 const char *sp = data->buf;
924 while (1) {
925 char *ep = strchr(sp, '\n');
926 int len;
927 if (!ep)
928 len = strlen(sp);
929 else
930 len = ep - sp;
931 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
932 if (!ep)
933 break;
934 sp = ep + 1;
938 static void handle_info(void)
940 struct strbuf *hdr;
941 int i;
943 for (i = 0; header[i]; i++) {
944 /* only print inbody headers if we output a patch file */
945 if (patch_lines && s_hdr_data[i])
946 hdr = s_hdr_data[i];
947 else if (p_hdr_data[i])
948 hdr = p_hdr_data[i];
949 else
950 continue;
952 if (!strcmp(header[i], "Subject")) {
953 if (!keep_subject) {
954 cleanup_subject(hdr);
955 cleanup_space(hdr);
957 output_header_lines(fout, "Subject", hdr);
958 } else if (!strcmp(header[i], "From")) {
959 cleanup_space(hdr);
960 handle_from(hdr);
961 fprintf(fout, "Author: %s\n", name.buf);
962 fprintf(fout, "Email: %s\n", email.buf);
963 } else {
964 cleanup_space(hdr);
965 fprintf(fout, "%s: %s\n", header[i], hdr->buf);
968 fprintf(fout, "\n");
971 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
973 int peek;
974 fin = in;
975 fout = out;
977 cmitmsg = fopen(msg, "w");
978 if (!cmitmsg) {
979 perror(msg);
980 return -1;
982 patchfile = fopen(patch, "w");
983 if (!patchfile) {
984 perror(patch);
985 fclose(cmitmsg);
986 return -1;
989 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
990 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
992 do {
993 peek = fgetc(in);
994 } while (isspace(peek));
995 ungetc(peek, in);
997 /* process the email header */
998 while (read_one_header_line(&line, fin))
999 check_header(&line, p_hdr_data, 1);
1001 handle_body();
1002 fclose(patchfile);
1004 handle_info();
1006 return 0;
1009 static int git_mailinfo_config(const char *var, const char *value, void *unused)
1011 if (!starts_with(var, "mailinfo."))
1012 return git_default_config(var, value, unused);
1013 if (!strcmp(var, "mailinfo.scissors")) {
1014 use_scissors = git_config_bool(var, value);
1015 return 0;
1017 /* perhaps others here */
1018 return 0;
1021 static const char mailinfo_usage[] =
1022 "git mailinfo [-k | -b] [-m | --message-id] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] <msg> <patch> < mail >info";
1024 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1026 const char *def_charset;
1028 /* NEEDSWORK: might want to do the optional .git/ directory
1029 * discovery
1031 git_config(git_mailinfo_config, NULL);
1033 def_charset = get_commit_output_encoding();
1034 metainfo_charset = def_charset;
1036 while (1 < argc && argv[1][0] == '-') {
1037 if (!strcmp(argv[1], "-k"))
1038 keep_subject = 1;
1039 else if (!strcmp(argv[1], "-b"))
1040 keep_non_patch_brackets_in_subject = 1;
1041 else if (!strcmp(argv[1], "-m") || !strcmp(argv[1], "--message-id"))
1042 add_message_id = 1;
1043 else if (!strcmp(argv[1], "-u"))
1044 metainfo_charset = def_charset;
1045 else if (!strcmp(argv[1], "-n"))
1046 metainfo_charset = NULL;
1047 else if (starts_with(argv[1], "--encoding="))
1048 metainfo_charset = argv[1] + 11;
1049 else if (!strcmp(argv[1], "--scissors"))
1050 use_scissors = 1;
1051 else if (!strcmp(argv[1], "--no-scissors"))
1052 use_scissors = 0;
1053 else if (!strcmp(argv[1], "--no-inbody-headers"))
1054 use_inbody_headers = 0;
1055 else
1056 usage(mailinfo_usage);
1057 argc--; argv++;
1060 if (argc != 3)
1061 usage(mailinfo_usage);
1063 return !!mailinfo(stdin, stdout, argv[1], argv[2]);