blob: e53ed9c0176d8070387404b349dfed98849af1a1 [file] [log] [blame]
Guido van Rossum56013131994-06-23 12:06:02 +00001# MH interface -- purely object-oriented (well, almost)
2#
3# Executive summary:
4#
5# import mhlib
6#
7# mh = mhlib.MH() # use default mailbox directory and profile
8# mh = mhlib.MH(mailbox) # override mailbox location (default from profile)
9# mh = mhlib.MH(mailbox, profile) # override mailbox and profile
10#
11# mh.error(format, ...) # print error message -- can be overridden
12# s = mh.getprofile(key) # profile entry (None if not set)
13# path = mh.getpath() # mailbox pathname
14# name = mh.getcontext() # name of current folder
15#
16# list = mh.listfolders() # names of top-level folders
17# list = mh.listallfolders() # names of all folders, including subfolders
18# list = mh.listsubfolders(name) # direct subfolders of given folder
19# list = mh.listallsubfolders(name) # all subfolders of given folder
20#
21# mh.makefolder(name) # create new folder
22# mh.deletefolder(name) # delete folder -- must have no subfolders
23#
24# f = mh.openfolder(name) # new open folder object
25#
26# f.error(format, ...) # same as mh.error(format, ...)
27# path = f.getfullname() # folder's full pathname
28# path = f.getsequencesfilename() # full pathname of folder's sequences file
29# path = f.getmessagefilename(n) # full pathname of message n in folder
30#
31# list = f.listmessages() # list of messages in folder (as numbers)
32# n = f.getcurrent() # get current message
33# f.setcurrent(n) # set current message
Guido van Rossum40b2cfb1995-01-02 18:38:23 +000034# n = f.getlast() # get last message (0 if no messagse)
35# f.setlast(n) # set last message (internal use only)
Guido van Rossum56013131994-06-23 12:06:02 +000036#
37# dict = f.getsequences() # dictionary of sequences in folder {name: list}
38# f.putsequences(dict) # write sequences back to folder
39#
Guido van Rossum40b2cfb1995-01-02 18:38:23 +000040# f.removemessages(list) # remove messages in list from folder
41# f.refilemessages(list, tofolder) # move messages in list to other folder
42# f.movemessage(n, tofolder, ton) # move one message to a given destination
43# f.copymessage(n, tofolder, ton) # copy one message to a given destination
44#
Guido van Rossum56013131994-06-23 12:06:02 +000045# m = f.openmessage(n) # new open message object (costs a file descriptor)
Guido van Rossum85347411994-09-09 11:10:15 +000046# m is a derived class of mimetools.Message(rfc822.Message), with:
Guido van Rossum56013131994-06-23 12:06:02 +000047# s = m.getheadertext() # text of message's headers
48# s = m.getheadertext(pred) # text of message's headers, filtered by pred
49# s = m.getbodytext() # text of message's body, decoded
50# s = m.getbodytext(0) # text of message's body, not decoded
51#
52# XXX To do, functionality:
Guido van Rossum56013131994-06-23 12:06:02 +000053# - annotate messages
54# - create, send messages
55#
Guido van Rossum40b2cfb1995-01-02 18:38:23 +000056# XXX To do, organization:
Guido van Rossum56013131994-06-23 12:06:02 +000057# - move IntSet to separate file
58# - move most Message functionality to module mimetools
59
60
61# Customizable defaults
62
63MH_PROFILE = '~/.mh_profile'
64PATH = '~/Mail'
65MH_SEQUENCES = '.mh_sequences'
66FOLDER_PROTECT = 0700
67
68
69# Imported modules
70
71import os
72from stat import ST_NLINK
73import regex
74import string
75import mimetools
76import multifile
Guido van Rossum40b2cfb1995-01-02 18:38:23 +000077import shutil
Guido van Rossum56013131994-06-23 12:06:02 +000078
79
80# Exported constants
81
82Error = 'mhlib.Error'
83
84
85# Class representing a particular collection of folders.
86# Optional constructor arguments are the pathname for the directory
87# containing the collection, and the MH profile to use.
88# If either is omitted or empty a default is used; the default
89# directory is taken from the MH profile if it is specified there.
90
91class MH:
92
93 # Constructor
94 def __init__(self, path = None, profile = None):
95 if not profile: profile = MH_PROFILE
96 self.profile = os.path.expanduser(profile)
97 if not path: path = self.getprofile('Path')
98 if not path: path = PATH
99 if not os.path.isabs(path) and path[0] != '~':
100 path = os.path.join('~', path)
101 path = os.path.expanduser(path)
102 if not os.path.isdir(path): raise Error, 'MH() path not found'
103 self.path = path
104
105 # String representation
106 def __repr__(self):
107 return 'MH(%s, %s)' % (`self.path`, `self.profile`)
108
109 # Routine to print an error. May be overridden by a derived class
110 def error(self, msg, *args):
111 sys.stderr.write('MH error: %\n' % (msg % args))
112
113 # Return a profile entry, None if not found
114 def getprofile(self, key):
115 return pickline(self.profile, key)
116
117 # Return the path (the name of the collection's directory)
118 def getpath(self):
119 return self.path
120
121 # Return the name of the current folder
122 def getcontext(self):
123 context = pickline(os.path.join(self.getpath(), 'context'),
124 'Current-Folder')
125 if not context: context = 'inbox'
126 return context
127
128 # Return the names of the top-level folders
129 def listfolders(self):
130 folders = []
131 path = self.getpath()
132 for name in os.listdir(path):
133 if name in (os.curdir, os.pardir): continue
134 fullname = os.path.join(path, name)
135 if os.path.isdir(fullname):
136 folders.append(name)
137 folders.sort()
138 return folders
139
140 # Return the names of the subfolders in a given folder
141 # (prefixed with the given folder name)
142 def listsubfolders(self, name):
143 fullname = os.path.join(self.path, name)
144 # Get the link count so we can avoid listing folders
145 # that have no subfolders.
146 st = os.stat(fullname)
147 nlinks = st[ST_NLINK]
148 if nlinks <= 2:
149 return []
150 subfolders = []
151 subnames = os.listdir(fullname)
152 for subname in subnames:
153 if subname in (os.curdir, os.pardir): continue
154 fullsubname = os.path.join(fullname, subname)
155 if os.path.isdir(fullsubname):
156 name_subname = os.path.join(name, subname)
157 subfolders.append(name_subname)
158 # Stop looking for subfolders when
159 # we've seen them all
160 nlinks = nlinks - 1
161 if nlinks <= 2:
162 break
163 subfolders.sort()
164 return subfolders
165
166 # Return the names of all folders, including subfolders, recursively
167 def listallfolders(self):
168 return self.listallsubfolders('')
169
170 # Return the names of subfolders in a given folder, recursively
171 def listallsubfolders(self, name):
172 fullname = os.path.join(self.path, name)
173 # Get the link count so we can avoid listing folders
174 # that have no subfolders.
175 st = os.stat(fullname)
176 nlinks = st[ST_NLINK]
177 if nlinks <= 2:
178 return []
179 subfolders = []
180 subnames = os.listdir(fullname)
181 for subname in subnames:
182 if subname in (os.curdir, os.pardir): continue
183 if subname[0] == ',' or isnumeric(subname): continue
184 fullsubname = os.path.join(fullname, subname)
185 if os.path.isdir(fullsubname):
186 name_subname = os.path.join(name, subname)
187 subfolders.append(name_subname)
188 if not os.path.islink(fullsubname):
189 subsubfolders = self.listallsubfolders(
190 name_subname)
191 subfolders = subfolders + subsubfolders
192 # Stop looking for subfolders when
193 # we've seen them all
194 nlinks = nlinks - 1
195 if nlinks <= 2:
196 break
197 subfolders.sort()
198 return subfolders
199
200 # Return a new Folder object for the named folder
201 def openfolder(self, name):
202 return Folder(self, name)
203
204 # Create a new folder. This raises os.error if the folder
205 # cannot be created
206 def makefolder(self, name):
207 protect = pickline(self.profile, 'Folder-Protect')
208 if protect and isnumeric(protect):
209 mode = eval('0' + protect)
210 else:
211 mode = FOLDER_PROTECT
212 os.mkdir(os.path.join(self.getpath(), name), mode)
213
214 # Delete a folder. This removes files in the folder but not
215 # subdirectories. If deleting the folder itself fails it
216 # raises os.error
217 def deletefolder(self, name):
218 fullname = os.path.join(self.getpath(), name)
219 for subname in os.listdir(fullname):
220 if subname in (os.curdir, os.pardir): continue
221 fullsubname = os.path.join(fullname, subname)
222 try:
223 os.unlink(fullsubname)
224 except os.error:
225 self.error('%s not deleted, continuing...' %
226 fullsubname)
227 os.rmdir(fullname)
228
229
230# Class representing a particular folder
231
232numericprog = regex.compile('[1-9][0-9]*')
233def isnumeric(str):
234 return numericprog.match(str) == len(str)
235
236class Folder:
237
238 # Constructor
239 def __init__(self, mh, name):
240 self.mh = mh
241 self.name = name
242 if not os.path.isdir(self.getfullname()):
243 raise Error, 'no folder %s' % name
244
245 # String representation
246 def __repr__(self):
247 return 'Folder(%s, %s)' % (`self.mh`, `self.name`)
248
249 # Error message handler
250 def error(self, *args):
251 apply(self.mh.error, args)
252
253 # Return the full pathname of the folder
254 def getfullname(self):
255 return os.path.join(self.mh.path, self.name)
256
257 # Return the full pathname of the folder's sequences file
258 def getsequencesfilename(self):
259 return os.path.join(self.getfullname(), MH_SEQUENCES)
260
261 # Return the full pathname of a message in the folder
262 def getmessagefilename(self, n):
263 return os.path.join(self.getfullname(), str(n))
264
265 # Return list of direct subfolders
266 def listsubfolders(self):
267 return self.mh.listsubfolders(self.name)
268
269 # Return list of all subfolders
270 def listallsubfolders(self):
271 return self.mh.listallsubfolders(self.name)
272
273 # Return the list of messages currently present in the folder.
274 # As a side effect, set self.last to the last message (or 0)
275 def listmessages(self):
276 messages = []
277 for name in os.listdir(self.getfullname()):
278 if isnumeric(name):
279 messages.append(eval(name))
280 messages.sort()
281 if messages:
282 self.last = max(messages)
283 else:
284 self.last = 0
285 return messages
286
287 # Return the set of sequences for the folder
288 def getsequences(self):
289 sequences = {}
290 fullname = self.getsequencesfilename()
291 try:
292 f = open(fullname, 'r')
293 except IOError:
294 return sequences
295 while 1:
296 line = f.readline()
297 if not line: break
298 fields = string.splitfields(line, ':')
299 if len(fields) <> 2:
300 self.error('bad sequence in %s: %s' %
301 (fullname, string.strip(line)))
302 key = string.strip(fields[0])
303 value = IntSet(string.strip(fields[1]), ' ').tolist()
304 sequences[key] = value
305 return sequences
306
307 # Write the set of sequences back to the folder
308 def putsequences(self, sequences):
309 fullname = self.getsequencesfilename()
Guido van Rossum85347411994-09-09 11:10:15 +0000310 f = None
Guido van Rossum56013131994-06-23 12:06:02 +0000311 for key in sequences.keys():
312 s = IntSet('', ' ')
313 s.fromlist(sequences[key])
Guido van Rossum85347411994-09-09 11:10:15 +0000314 if not f: f = open(fullname, 'w')
Guido van Rossum56013131994-06-23 12:06:02 +0000315 f.write('%s: %s\n' % (key, s.tostring()))
Guido van Rossum85347411994-09-09 11:10:15 +0000316 if not f:
317 try:
318 os.unlink(fullname)
319 except os.error:
320 pass
321 else:
322 f.close()
Guido van Rossum56013131994-06-23 12:06:02 +0000323
324 # Return the current message. Raise KeyError when there is none
325 def getcurrent(self):
326 return min(self.getsequences()['cur'])
327
328 # Set the current message
329 def setcurrent(self, n):
330 updateline(self.getsequencesfilename(), 'cur', str(n), 0)
331
Guido van Rossum85347411994-09-09 11:10:15 +0000332 # Open a message -- returns a Message object
Guido van Rossum56013131994-06-23 12:06:02 +0000333 def openmessage(self, n):
334 path = self.getmessagefilename(n)
335 return Message(self, n)
336
337 # Remove one or more messages -- may raise os.error
338 def removemessages(self, list):
339 errors = []
340 deleted = []
341 for n in list:
342 path = self.getmessagefilename(n)
343 commapath = self.getmessagefilename(',' + str(n))
344 try:
345 os.unlink(commapath)
346 except os.error:
347 pass
348 try:
349 os.rename(path, commapath)
350 except os.error, msg:
351 errors.append(msg)
352 else:
353 deleted.append(n)
354 if deleted:
355 self.removefromallsequences(deleted)
356 if errors:
357 if len(errors) == 1:
358 raise os.error, errors[0]
359 else:
360 raise os.error, ('multiple errors:', errors)
361
362 # Refile one or more messages -- may raise os.error.
363 # 'tofolder' is an open folder object
364 def refilemessages(self, list, tofolder):
365 errors = []
366 refiled = []
367 for n in list:
368 ton = tofolder.getlast() + 1
369 path = self.getmessagefilename(n)
370 topath = tofolder.getmessagefilename(ton)
371 try:
372 os.rename(path, topath)
Guido van Rossum40b2cfb1995-01-02 18:38:23 +0000373 except os.error:
374 # Try copying
375 try:
376 shutil.copy2(path, topath)
377 os.unlink(path)
378 except (IOError, os.error), msg:
379 errors.append(msg)
380 try:
381 os.unlink(topath)
382 except os.error:
383 pass
384 continue
385 tofolder.setlast(ton)
386 refiled.append(n)
Guido van Rossum56013131994-06-23 12:06:02 +0000387 if refiled:
388 self.removefromallsequences(refiled)
389 if errors:
390 if len(errors) == 1:
391 raise os.error, errors[0]
392 else:
393 raise os.error, ('multiple errors:', errors)
394
Guido van Rossum40b2cfb1995-01-02 18:38:23 +0000395 # Move one message over a specific destination message,
396 # which may or may not already exist.
397 def movemessage(self, n, tofolder, ton):
398 path = self.getmessagefilename(n)
399 # Open it to check that it exists
400 f = open(path)
401 f.close()
402 del f
403 topath = tofolder.getmessagefilename(ton)
404 backuptopath = tofolder.getmessagefilename(',%d' % ton)
405 try:
406 os.rename(topath, backuptopath)
407 except os.error:
408 pass
409 try:
410 os.rename(path, topath)
411 except os.error:
412 # Try copying
413 ok = 0
414 try:
415 tofolder.setlast(None)
416 shutil.copy2(path, topath)
417 ok = 1
418 finally:
419 if not ok:
420 try:
421 os.unlink(topath)
422 except os.error:
423 pass
424 os.unlink(path)
425 self.removefromallsequences([n])
426
427 # Copy one message over a specific destination message,
428 # which may or may not already exist.
429 def copymessage(self, n, tofolder, ton):
430 path = self.getmessagefilename(n)
431 # Open it to check that it exists
432 f = open(path)
433 f.close()
434 del f
435 topath = tofolder.getmessagefilename(ton)
436 backuptopath = tofolder.getmessagefilename(',%d' % ton)
437 try:
438 os.rename(topath, backuptopath)
439 except os.error:
440 pass
441 ok = 0
442 try:
443 tofolder.setlast(None)
444 shutil.copy2(path, topath)
445 ok = 1
446 finally:
447 if not ok:
448 try:
449 os.unlink(topath)
450 except os.error:
451 pass
452
Guido van Rossum56013131994-06-23 12:06:02 +0000453 # Remove one or more messages from all sequeuces (including last)
454 def removefromallsequences(self, list):
455 if hasattr(self, 'last') and self.last in list:
456 del self.last
457 sequences = self.getsequences()
458 changed = 0
459 for name, seq in sequences.items():
460 for n in list:
461 if n in seq:
462 seq.remove(n)
463 changed = 1
464 if not seq:
465 del sequences[name]
466 if changed:
Guido van Rossum5f47e571994-07-14 14:01:00 +0000467 self.putsequences(sequences)
Guido van Rossum56013131994-06-23 12:06:02 +0000468
469 # Return the last message number
470 def getlast(self):
471 if not hasattr(self, 'last'):
472 messages = self.listmessages()
473 return self.last
474
475 # Set the last message number
476 def setlast(self, last):
477 if last is None:
478 if hasattr(self, 'last'):
479 del self.last
480 else:
481 self.last = last
482
483class Message(mimetools.Message):
484
485 # Constructor
486 def __init__(self, f, n, fp = None):
487 self.folder = f
488 self.number = n
489 if not fp:
490 path = f.getmessagefilename(n)
491 fp = open(path, 'r')
492 mimetools.Message.__init__(self, fp)
493
494 # String representation
495 def __repr__(self):
496 return 'Message(%s, %s)' % (repr(self.folder), self.number)
497
498 # Return the message's header text as a string. If an
499 # argument is specified, it is used as a filter predicate to
500 # decide which headers to return (its argument is the header
501 # name converted to lower case).
502 def getheadertext(self, pred = None):
503 if not pred:
504 return string.joinfields(self.headers, '')
505 headers = []
506 hit = 0
507 for line in self.headers:
508 if line[0] not in string.whitespace:
509 i = string.find(line, ':')
510 if i > 0:
511 hit = pred(string.lower(line[:i]))
512 if hit: headers.append(line)
513 return string.joinfields(headers, '')
514
515 # Return the message's body text as string. This undoes a
516 # Content-Transfer-Encoding, but does not interpret other MIME
517 # features (e.g. multipart messages). To suppress to
518 # decoding, pass a 0 as argument
519 def getbodytext(self, decode = 1):
520 self.fp.seek(self.startofbody)
521 encoding = self.getencoding()
522 if not decode or encoding in ('7bit', '8bit', 'binary'):
523 return self.fp.read()
524 from StringIO import StringIO
525 output = StringIO()
526 mimetools.decode(self.fp, output, encoding)
527 return output.getvalue()
528
529 # Only for multipart messages: return the message's body as a
530 # list of SubMessage objects. Each submessage object behaves
531 # (almost) as a Message object.
532 def getbodyparts(self):
533 if self.getmaintype() != 'multipart':
534 raise Error, \
535 'Content-Type is not multipart/*'
536 bdry = self.getparam('boundary')
537 if not bdry:
538 raise Error, 'multipart/* without boundary param'
539 self.fp.seek(self.startofbody)
540 mf = multifile.MultiFile(self.fp)
541 mf.push(bdry)
542 parts = []
543 while mf.next():
544 n = str(self.number) + '.' + `1 + len(parts)`
545 part = SubMessage(self.folder, n, mf)
546 parts.append(part)
547 mf.pop()
548 return parts
549
550 # Return body, either a string or a list of messages
551 def getbody(self):
552 if self.getmaintype() == 'multipart':
553 return self.getbodyparts()
554 else:
555 return self.getbodytext()
556
557
558class SubMessage(Message):
559
560 # Constructor
561 def __init__(self, f, n, fp):
562 Message.__init__(self, f, n, fp)
563 if self.getmaintype() == 'multipart':
564 self.body = Message.getbodyparts(self)
565 else:
566 self.body = Message.getbodytext(self)
567 # XXX If this is big, should remember file pointers
568
569 # String representation
570 def __repr__(self):
571 f, n, fp = self.folder, self.number, self.fp
572 return 'SubMessage(%s, %s, %s)' % (f, n, fp)
573
574 def getbodytext(self):
575 if type(self.body) == type(''):
576 return self.body
577
578 def getbodyparts(self):
579 if type(self.body) == type([]):
580 return self.body
581
582 def getbody(self):
583 return self.body
584
585
586# Class implementing sets of integers.
587#
588# This is an efficient representation for sets consisting of several
589# continuous ranges, e.g. 1-100,200-400,402-1000 is represented
590# internally as a list of three pairs: [(1,100), (200,400),
591# (402,1000)]. The internal representation is always kept normalized.
592#
593# The constructor has up to three arguments:
594# - the string used to initialize the set (default ''),
595# - the separator between ranges (default ',')
596# - the separator between begin and end of a range (default '-')
597# The separators may be regular expressions and should be different.
598#
599# The tostring() function yields a string that can be passed to another
600# IntSet constructor; __repr__() is a valid IntSet constructor itself.
601#
602# XXX The default begin/end separator means that negative numbers are
603# not supported very well.
604#
605# XXX There are currently no operations to remove set elements.
606
607class IntSet:
608
609 def __init__(self, data = None, sep = ',', rng = '-'):
610 self.pairs = []
611 self.sep = sep
612 self.rng = rng
613 if data: self.fromstring(data)
614
615 def reset(self):
616 self.pairs = []
617
618 def __cmp__(self, other):
619 return cmp(self.pairs, other.pairs)
620
621 def __hash__(self):
622 return hash(self.pairs)
623
624 def __repr__(self):
625 return 'IntSet(%s, %s, %s)' % (`self.tostring()`,
626 `self.sep`, `self.rng`)
627
628 def normalize(self):
629 self.pairs.sort()
630 i = 1
631 while i < len(self.pairs):
632 alo, ahi = self.pairs[i-1]
633 blo, bhi = self.pairs[i]
634 if ahi >= blo-1:
635 self.pairs[i-1:i+1] = [
636 (alo, max(ahi, bhi))]
637 else:
638 i = i+1
639
640 def tostring(self):
641 s = ''
642 for lo, hi in self.pairs:
643 if lo == hi: t = `lo`
644 else: t = `lo` + self.rng + `hi`
645 if s: s = s + (self.sep + t)
646 else: s = t
647 return s
648
649 def tolist(self):
650 l = []
651 for lo, hi in self.pairs:
652 m = range(lo, hi+1)
653 l = l + m
654 return l
655
656 def fromlist(self, list):
657 for i in list:
658 self.append(i)
659
660 def clone(self):
661 new = IntSet()
662 new.pairs = self.pairs[:]
663 return new
664
665 def min(self):
666 return self.pairs[0][0]
667
668 def max(self):
669 return self.pairs[-1][-1]
670
671 def contains(self, x):
672 for lo, hi in self.pairs:
673 if lo <= x <= hi: return 1
674 return 0
675
676 def append(self, x):
677 for i in range(len(self.pairs)):
678 lo, hi = self.pairs[i]
679 if x < lo: # Need to insert before
680 if x+1 == lo:
681 self.pairs[i] = (x, hi)
682 else:
683 self.pairs.insert(i, (x, x))
684 if i > 0 and x-1 == self.pairs[i-1][1]:
685 # Merge with previous
686 self.pairs[i-1:i+1] = [
687 (self.pairs[i-1][0],
688 self.pairs[i][1])
689 ]
690 return
691 if x <= hi: # Already in set
692 return
693 i = len(self.pairs) - 1
694 if i >= 0:
695 lo, hi = self.pairs[i]
696 if x-1 == hi:
697 self.pairs[i] = lo, x
698 return
699 self.pairs.append((x, x))
700
701 def addpair(self, xlo, xhi):
702 if xlo > xhi: return
703 self.pairs.append((xlo, xhi))
704 self.normalize()
705
706 def fromstring(self, data):
707 import string, regsub
708 new = []
709 for part in regsub.split(data, self.sep):
710 list = []
711 for subp in regsub.split(part, self.rng):
712 s = string.strip(subp)
713 list.append(string.atoi(s))
714 if len(list) == 1:
715 new.append((list[0], list[0]))
716 elif len(list) == 2 and list[0] <= list[1]:
717 new.append((list[0], list[1]))
718 else:
719 raise ValueError, 'bad data passed to IntSet'
720 self.pairs = self.pairs + new
721 self.normalize()
722
723
724# Subroutines to read/write entries in .mh_profile and .mh_sequences
725
726def pickline(file, key, casefold = 1):
727 try:
728 f = open(file, 'r')
729 except IOError:
730 return None
731 pat = key + ':'
732 if casefold:
733 prog = regex.compile(pat, regex.casefold)
734 else:
735 prog = regex.compile(pat)
736 while 1:
737 line = f.readline()
738 if not line: break
Guido van Rossumea8ee1d1995-01-26 00:45:20 +0000739 if prog.match(line) >= 0:
Guido van Rossum56013131994-06-23 12:06:02 +0000740 text = line[len(key)+1:]
741 while 1:
742 line = f.readline()
743 if not line or \
744 line[0] not in string.whitespace:
745 break
746 text = text + line
747 return string.strip(text)
748 return None
749
750def updateline(file, key, value, casefold = 1):
751 try:
752 f = open(file, 'r')
753 lines = f.readlines()
754 f.close()
755 except IOError:
756 lines = []
757 pat = key + ':\(.*\)\n'
758 if casefold:
759 prog = regex.compile(pat, regex.casefold)
760 else:
761 prog = regex.compile(pat)
762 if value is None:
763 newline = None
764 else:
765 newline = '%s: %s' % (key, value)
766 for i in range(len(lines)):
767 line = lines[i]
768 if prog.match(line) == len(line):
769 if newline is None:
770 del lines[i]
771 else:
772 lines[i] = newline
773 break
774 else:
775 if newline is not None:
776 lines.append(newline)
777 f = open(tempfile, 'w')
778 for line in lines:
779 f.write(line)
780 f.close()
781
782
783# Test program
784
785def test():
786 global mh, f
787 os.system('rm -rf $HOME/Mail/@test')
788 mh = MH()
789 def do(s): print s; print eval(s)
790 do('mh.listfolders()')
791 do('mh.listallfolders()')
792 testfolders = ['@test', '@test/test1', '@test/test2',
793 '@test/test1/test11', '@test/test1/test12',
794 '@test/test1/test11/test111']
795 for t in testfolders: do('mh.makefolder(%s)' % `t`)
796 do('mh.listsubfolders(\'@test\')')
797 do('mh.listallsubfolders(\'@test\')')
798 f = mh.openfolder('@test')
799 do('f.listsubfolders()')
800 do('f.listallsubfolders()')
801 do('f.getsequences()')
802 seqs = f.getsequences()
803 seqs['foo'] = IntSet('1-10 12-20', ' ').tolist()
804 print seqs
805 f.putsequences(seqs)
806 do('f.getsequences()')
807 testfolders.reverse()
808 for t in testfolders: do('mh.deletefolder(%s)' % `t`)
809 do('mh.getcontext()')
810 context = mh.getcontext()
811 f = mh.openfolder(context)
812 do('f.listmessages()')
813 do('f.getcurrent()')
814
815
816if __name__ == '__main__':
817 test()