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>
16 static const char git_mailsplit_usage[] =
17 "git-mailsplit [-d<prec>] [-f<n>] [-b] -o<directory> <mbox>...";
19 static int is_from_line(const char *line, int len)
23 if (len < 20 || memcmp("From ", line, 5))
26 colon = line + len - 2;
35 if (!isdigit(colon[-4]) ||
36 !isdigit(colon[-2]) ||
37 !isdigit(colon[-1]) ||
38 !isdigit(colon[ 1]) ||
43 if (strtol(colon+3, NULL, 10) <= 90)
46 /* Ok, close enough */
50 /* Could be as small as 64, enough to hold a Unix "From " line. */
51 static char buf[4096];
53 /* Called with the first line (potentially partial)
54 * already in buf[] -- normally that should begin with
55 * the Unix "From " line. Write it into the specified
58 static int split_one(FILE *mbox, const char *name, int allow_bare)
61 int len = strlen(buf);
64 int is_bare = !is_from_line(buf, len);
66 if (is_bare && !allow_bare)
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_bare && 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 nr = 0, nr_prec = 4;
109 const char *dir = NULL;
111 static const char *stdin_only[] = { "-", NULL };
114 for (argp = argv+1; *argp; argp++) {
115 const char *arg = *argp;
120 if ( arg[1] == 'd' ) {
121 nr_prec = strtol(arg+2, NULL, 10);
122 if (nr_prec < 3 || 10 <= nr_prec)
123 usage(git_mailsplit_usage);
125 } else if ( arg[1] == 'f' ) {
126 nr = strtol(arg+2, NULL, 10);
127 } else if ( arg[1] == 'b' && !arg[2] ) {
129 } else if ( arg[1] == 'o' && arg[2] ) {
131 } else if ( arg[1] == '-' && !arg[2] ) {
132 argp++; /* -- marks end of options */
135 die("unknown option: %s", arg);
140 /* Backwards compatibility: if no -o specified, accept
141 <mbox> <dir> or just <dir> */
142 switch (argc - (argp-argv)) {
148 stdin_only[0] = argp[0];
153 usage(git_mailsplit_usage);
156 /* New usage: if no more argument, parse stdin */
161 name = xmalloc(strlen(dir) + 2 + 3 * sizeof(nr));
164 const char *file = *argp++;
165 FILE *f = !strcmp(file, "-") ? stdin : fopen(file, "rt");
169 die ("cannot open mbox %s", file);
171 if (fgets(buf, sizeof(buf), f) == NULL) {
173 break; /* empty stdin is OK */
174 die("cannot read mbox %s", file);
178 sprintf(name, "%s/%0*d", dir, nr_prec, ++nr);
179 file_done = split_one(f, name, allow_bare);