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>
17 static const char git_mailsplit_usage[] =
18 "git-mailsplit [-d<prec>] [<mbox>] <directory>";
20 static int is_from_line(const char *line, int len)
24 if (len < 20 || memcmp("From ", line, 5))
27 colon = line + len - 2;
36 if (!isdigit(colon[-4]) ||
37 !isdigit(colon[-2]) ||
38 !isdigit(colon[-1]) ||
39 !isdigit(colon[ 1]) ||
44 if (strtol(colon+3, NULL, 10) <= 90)
47 /* Ok, close enough */
51 /* Could be as small as 64, enough to hold a Unix "From " line. */
52 static char buf[4096];
54 /* Called with the first line (potentially partial)
55 * already in buf[] -- normally that should begin with
56 * the Unix "From " line. Write it into the specified
59 static int split_one(FILE *mbox, const char *name)
62 int len = strlen(buf);
66 if (!is_from_line(buf, len))
69 fd = open(name, O_WRONLY | O_CREAT | O_EXCL, 0666);
71 die("cannot open output file %s", name);
72 output = fdopen(fd, "w");
74 /* Copy it out, while searching for a line that begins with
75 * "From " and having something that looks like a date format.
78 int is_partial = (buf[len-1] != '\n');
80 if (fputs(buf, output) == EOF)
81 die("cannot write output");
83 if (fgets(buf, sizeof(buf), mbox) == NULL) {
88 die("cannot read mbox");
91 if (!is_partial && is_from_line(buf, len))
92 break; /* done with one message */
101 fprintf(stderr, "corrupt mailbox\n");
105 int main(int argc, const char **argv)
107 int i, nr, nr_prec = 4;
110 for (i = 1; i < argc; i++) {
111 const char *arg = argv[i];
116 if (!strncmp(arg, "-d", 2)) {
117 nr_prec = strtol(arg + 2, NULL, 10);
118 if (nr_prec < 3 || 10 <= nr_prec)
119 usage(git_mailsplit_usage);
124 /* Either one remaining arg (dir), or two (mbox and dir) */
130 if ((mbox = fopen(argv[i], "r")) == NULL)
131 die("cannot open mbox %s for reading", argv[i]);
134 usage(git_mailsplit_usage);
136 if (chdir(argv[argc - 1]) < 0)
137 usage(git_mailsplit_usage);
140 if (fgets(buf, sizeof(buf), mbox) == NULL)
141 die("cannot read mbox");
146 sprintf(name, "%0*d", nr_prec, ++nr);
147 switch (split_one(mbox, name)) {