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>] [-f<n>] [-b] -o<directory> <mbox>...";
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, int allow_bare)
62 int len = strlen(buf);
65 int is_bare = !is_from_line(buf, len);
67 if (is_bare && !allow_bare)
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_bare && 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 nr = 0, nr_prec = 4;
110 const char *dir = NULL;
112 static const char *stdin_only[] = { "-", NULL };
115 for (argp = argv+1; *argp; argp++) {
116 const char *arg = *argp;
121 if ( arg[1] == 'd' ) {
122 nr_prec = strtol(arg+2, NULL, 10);
123 if (nr_prec < 3 || 10 <= nr_prec)
124 usage(git_mailsplit_usage);
126 } else if ( arg[1] == 'f' ) {
127 nr = strtol(arg+2, NULL, 10);
128 } else if ( arg[1] == 'b' && !arg[2] ) {
130 } else if ( arg[1] == 'o' && arg[2] ) {
132 } else if ( arg[1] == '-' && !arg[2] ) {
133 argp++; /* -- marks end of options */
136 die("unknown option: %s", arg);
141 /* Backwards compatibility: if no -o specified, accept
142 <mbox> <dir> or just <dir> */
143 switch (argc - (argp-argv)) {
149 stdin_only[0] = argp[0];
154 usage(git_mailsplit_usage);
157 /* New usage: if no more argument, parse stdin */
162 name = xmalloc(strlen(dir) + 2 + 3 * sizeof(nr));
165 const char *file = *argp++;
166 FILE *f = !strcmp(file, "-") ? stdin : fopen(file, "rt");
170 die ("cannot open mbox %s", file);
172 if (fgets(buf, sizeof(buf), f) == NULL)
173 die("cannot read mbox %s", file);
176 sprintf(name, "%s/%0*d", dir, nr_prec, ++nr);
177 file_done = split_one(f, name, allow_bare);