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>
18 static const char git_mailsplit_usage[] =
19 "git-mailsplit [-d<prec>] [<mbox>] <directory>";
21 static int is_from_line(const char *line, int len)
25 if (len < 20 || memcmp("From ", line, 5))
28 colon = line + len - 2;
37 if (!isdigit(colon[-4]) ||
38 !isdigit(colon[-2]) ||
39 !isdigit(colon[-1]) ||
40 !isdigit(colon[ 1]) ||
45 if (strtol(colon+3, NULL, 10) <= 90)
48 /* Ok, close enough */
52 /* Could be as small as 64, enough to hold a Unix "From " line. */
53 static char buf[4096];
55 /* Called with the first line (potentially partial)
56 * already in buf[] -- normally that should begin with
57 * the Unix "From " line. Write it into the specified
60 static int split_one(FILE *mbox, const char *name)
63 int len = strlen(buf);
67 if (!is_from_line(buf, len))
70 fd = open(name, O_WRONLY | O_CREAT | O_EXCL, 0666);
72 die("cannot open output file %s", name);
73 output = fdopen(fd, "w");
75 /* Copy it out, while searching for a line that begins with
76 * "From " and having something that looks like a date format.
79 int is_partial = (buf[len-1] != '\n');
81 if (fputs(buf, output) == EOF)
82 die("cannot write output");
84 if (fgets(buf, sizeof(buf), mbox) == NULL) {
89 die("cannot read mbox");
92 if (!is_partial && is_from_line(buf, len))
93 break; /* done with one message */
102 fprintf(stderr, "corrupt mailbox\n");
106 int main(int argc, const char **argv)
108 int i, nr, nr_prec = 4;
111 for (i = 1; i < argc; i++) {
112 const char *arg = argv[i];
117 if (!strncmp(arg, "-d", 2)) {
118 nr_prec = strtol(arg + 2, NULL, 10);
119 if (nr_prec < 3 || 10 <= nr_prec)
120 usage(git_mailsplit_usage);
125 /* Either one remaining arg (dir), or two (mbox and dir) */
131 if ((mbox = fopen(argv[i], "r")) == NULL)
132 die("cannot open mbox %s for reading", argv[i]);
135 usage(git_mailsplit_usage);
137 if (chdir(argv[argc - 1]) < 0)
138 usage(git_mailsplit_usage);
141 if (fgets(buf, sizeof(buf), mbox) == NULL)
142 die("cannot read mbox");
147 sprintf(name, "%0*d", nr_prec, ++nr);
148 switch (split_one(mbox, name)) {