]> git.ipfire.org Git - thirdparty/kernel/stable-queue.git/blob - scripts/splitmbox.py
5.4-stable patches
[thirdparty/kernel/stable-queue.git] / scripts / splitmbox.py
1 #! /usr/bin/env python3
2 """ Split a Unix-style mailbox into individual files
3
4 Written by Aquarius <aquarius@kryogenix.org>
5 Usage: splitmbox.py <mailbox-file> <directory>
6
7 This will create files numbered 01,02,03... in <directory>. The
8 number of prefixed zeroes will make all filenames in the
9 directory the same length. """
10
11 import mailbox,sys,getopt,string,os,subprocess
12
13 VERSION = '0.1'
14 USAGE = """Usage: splitmbox.py [ OPTION ] <mailbox-file> <directory>
15
16 -h, --help
17 Show this help text and exit
18 -v, --version
19 Show file version and exit
20
21 This will create files numbered 01,02,03... in <directory>. The
22 number of prefixed zeroes will make all filenames in the
23 directory the same length. """
24
25
26 try:
27 optlist, args = getopt.getopt(sys.argv[1:],'hv',['help','version'])
28 except getopt.error, error_text:
29 print error_text,'\n'
30 print USAGE
31 sys.exit(1)
32
33 for tuple in optlist:
34 if tuple[0] == '-h' or tuple[0] == '--help':
35 print USAGE
36 sys.exit(0)
37 if tuple[0] == '-v' or tuple[0] == '--version':
38 print VERSION
39 sys.exit(0)
40
41 if len(args) != 2:
42 print USAGE
43
44 mbox_fname, output_dir = args
45 if output_dir[-1] != '/':
46 output_dir = output_dir + '/'
47
48 # Make the output directory, if required
49 try:
50 os.mkdir(output_dir)
51 except os.error,ertxt:
52 if string.find(str(ertxt),'File exists') == -1:
53 print 'Failed to create or use directory',output_dir,'[',ertxt,']'
54 sys.exit(1)
55
56 try:
57 mbox_file = open(mbox_fname)
58 except:
59 print "Failed to open file",mbox_fname
60 sys.exit(1)
61
62 mbox = mailbox.UnixMailbox(mbox_file)
63
64 # Find out how many messages in the mailbox
65 count = 0
66 while 1:
67 msg = mbox.next()
68 if not msg:
69 break
70 count = count + 1
71
72 # Now do it again, outputting files
73
74 mbox_file.close()
75 mbox_file = open(mbox_fname)
76 mbox = mailbox.UnixMailbox(mbox_file)
77
78 digits = len(str(count))
79 #digits = 3
80 count = 0
81 while 1:
82 msg = mbox.next()
83 if not msg:
84 break
85 fname = output_dir+'msg.'+('0'*digits+str(count))[-digits:]
86 print 'Writing ', fname
87 outfile = open(fname,'w')
88 outfile.write('From foo@baz ');
89 outfile.write(subprocess.check_output('date'));
90 for s in msg.headers:
91 outfile.write(s)
92 outfile.write('\n')
93 for s in msg.fp.readlines():
94 outfile.write(s)
95 outfile.close()
96 count = count + 1