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