2 * Totally braindamaged mbox splitter program.
4 * It just splits a mbox into a list of files: "0001" "0002" ..
5 * so you can process them further from there.
10 #include <sys/types.h>
19 static const char git_mailsplit_usage
[] =
20 "git-mailsplit [-d<prec>] [<mbox>] <directory>";
22 static int is_from_line(const char *line
, int len
)
26 if (len
< 20 || memcmp("From ", line
, 5))
29 colon
= line
+ len
- 2;
38 if (!isdigit(colon
[-4]) ||
39 !isdigit(colon
[-2]) ||
40 !isdigit(colon
[-1]) ||
41 !isdigit(colon
[ 1]) ||
46 if (strtol(colon
+3, NULL
, 10) <= 90)
49 /* Ok, close enough */
53 /* Could be as small as 64, enough to hold a Unix "From " line. */
54 static char buf
[4096];
56 /* Called with the first line (potentially partial)
57 * already in buf[] -- normally that should begin with
58 * the Unix "From " line. Write it into the specified
61 static int split_one(FILE *mbox
, const char *name
)
64 int len
= strlen(buf
);
68 if (!is_from_line(buf
, len
))
71 fd
= open(name
, O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
73 die("cannot open output file %s", name
);
74 output
= fdopen(fd
, "w");
76 /* Copy it out, while searching for a line that begins with
77 * "From " and having something that looks like a date format.
80 int is_partial
= (buf
[len
-1] != '\n');
82 if (fputs(buf
, output
) == EOF
)
83 die("cannot write output");
85 if (fgets(buf
, sizeof(buf
), mbox
) == NULL
) {
90 die("cannot read mbox");
93 if (!is_partial
&& is_from_line(buf
, len
))
94 break; /* done with one message */
103 fprintf(stderr
, "corrupt mailbox\n");
107 int main(int argc
, const char **argv
)
109 int i
, nr
, nr_prec
= 4;
112 for (i
= 1; i
< argc
; i
++) {
113 const char *arg
= argv
[i
];
118 if (!strncmp(arg
, "-d", 2)) {
119 nr_prec
= strtol(arg
+ 2, NULL
, 10);
120 if (nr_prec
< 3 || 10 <= nr_prec
)
121 usage(git_mailsplit_usage
);
126 /* Either one remaining arg (dir), or two (mbox and dir) */
132 if ((mbox
= fopen(argv
[i
], "r")) == NULL
)
133 die("cannot open mbox %s for reading", argv
[i
]);
136 usage(git_mailsplit_usage
);
138 if (chdir(argv
[argc
- 1]) < 0)
139 usage(git_mailsplit_usage
);
142 if (fgets(buf
, sizeof(buf
), mbox
) == NULL
)
143 die("cannot read mbox");
148 sprintf(name
, "%0*d", nr_prec
, ++nr
);
149 switch (split_one(mbox
, name
)) {