blob: f8599b795b4523d496021f47334519ef148bf2ad [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
Guido van Rossum6d6a15b1996-07-21 02:18:22 +0000412 def refilemessages(self, list, tofolder, keepsequences=0):
Guido van Rossum56013131994-06-23 12:06:02 +0000413 errors = []
Guido van Rossum6d6a15b1996-07-21 02:18:22 +0000414 refiled = {}
Guido van Rossum56013131994-06-23 12:06:02 +0000415 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)
Guido van Rossum6d6a15b1996-07-21 02:18:22 +0000434 refiled[n] = ton
Guido van Rossum56013131994-06-23 12:06:02 +0000435 if refiled:
Guido van Rossum6d6a15b1996-07-21 02:18:22 +0000436 if keepsequences:
437 tofolder._copysequences(self, refiled.items())
438 self.removefromallsequences(refiled.keys())
Guido van Rossum56013131994-06-23 12:06:02 +0000439 if errors:
440 if len(errors) == 1:
441 raise os.error, errors[0]
442 else:
443 raise os.error, ('multiple errors:', errors)
444
Guido van Rossum6d6a15b1996-07-21 02:18:22 +0000445 # Helper for refilemessages() to copy sequences
446 def _copysequences(self, fromfolder, refileditems):
447 fromsequences = fromfolder.getsequences()
448 tosequences = self.getsequences()
449 changed = 0
450 for name, seq in fromsequences.items():
451 try:
452 toseq = tosequences[name]
453 new = 0
454 except:
455 toseq = []
456 new = 1
457 for fromn, ton in refileditems:
458 if fromn in seq:
459 toseq.append(ton)
460 changed = 1
461 if new and toseq:
462 tosequences[name] = toseq
463 if changed:
464 self.putsequences(tosequences)
465
Guido van Rossum40b2cfb1995-01-02 18:38:23 +0000466 # Move one message over a specific destination message,
467 # which may or may not already exist.
468 def movemessage(self, n, tofolder, ton):
469 path = self.getmessagefilename(n)
470 # Open it to check that it exists
471 f = open(path)
472 f.close()
473 del f
474 topath = tofolder.getmessagefilename(ton)
475 backuptopath = tofolder.getmessagefilename(',%d' % ton)
476 try:
477 os.rename(topath, backuptopath)
478 except os.error:
479 pass
480 try:
481 os.rename(path, topath)
482 except os.error:
483 # Try copying
484 ok = 0
485 try:
486 tofolder.setlast(None)
487 shutil.copy2(path, topath)
488 ok = 1
489 finally:
490 if not ok:
491 try:
492 os.unlink(topath)
493 except os.error:
494 pass
495 os.unlink(path)
496 self.removefromallsequences([n])
497
498 # Copy one message over a specific destination message,
499 # which may or may not already exist.
500 def copymessage(self, n, tofolder, ton):
501 path = self.getmessagefilename(n)
502 # Open it to check that it exists
503 f = open(path)
504 f.close()
505 del f
506 topath = tofolder.getmessagefilename(ton)
507 backuptopath = tofolder.getmessagefilename(',%d' % ton)
508 try:
509 os.rename(topath, backuptopath)
510 except os.error:
511 pass
512 ok = 0
513 try:
514 tofolder.setlast(None)
515 shutil.copy2(path, topath)
516 ok = 1
517 finally:
518 if not ok:
519 try:
520 os.unlink(topath)
521 except os.error:
522 pass
523
Guido van Rossum56013131994-06-23 12:06:02 +0000524 # Remove one or more messages from all sequeuces (including last)
525 def removefromallsequences(self, list):
526 if hasattr(self, 'last') and self.last in list:
527 del self.last
528 sequences = self.getsequences()
529 changed = 0
530 for name, seq in sequences.items():
531 for n in list:
532 if n in seq:
533 seq.remove(n)
534 changed = 1
535 if not seq:
536 del sequences[name]
537 if changed:
Guido van Rossum5f47e571994-07-14 14:01:00 +0000538 self.putsequences(sequences)
Guido van Rossum56013131994-06-23 12:06:02 +0000539
540 # Return the last message number
541 def getlast(self):
542 if not hasattr(self, 'last'):
543 messages = self.listmessages()
544 return self.last
545
546 # Set the last message number
547 def setlast(self, last):
548 if last is None:
549 if hasattr(self, 'last'):
550 del self.last
551 else:
552 self.last = last
553
554class Message(mimetools.Message):
555
556 # Constructor
557 def __init__(self, f, n, fp = None):
558 self.folder = f
559 self.number = n
560 if not fp:
561 path = f.getmessagefilename(n)
562 fp = open(path, 'r')
563 mimetools.Message.__init__(self, fp)
564
565 # String representation
566 def __repr__(self):
567 return 'Message(%s, %s)' % (repr(self.folder), self.number)
568
569 # Return the message's header text as a string. If an
570 # argument is specified, it is used as a filter predicate to
571 # decide which headers to return (its argument is the header
572 # name converted to lower case).
573 def getheadertext(self, pred = None):
574 if not pred:
575 return string.joinfields(self.headers, '')
576 headers = []
577 hit = 0
578 for line in self.headers:
579 if line[0] not in string.whitespace:
580 i = string.find(line, ':')
581 if i > 0:
582 hit = pred(string.lower(line[:i]))
583 if hit: headers.append(line)
584 return string.joinfields(headers, '')
585
586 # Return the message's body text as string. This undoes a
587 # Content-Transfer-Encoding, but does not interpret other MIME
588 # features (e.g. multipart messages). To suppress to
589 # decoding, pass a 0 as argument
590 def getbodytext(self, decode = 1):
591 self.fp.seek(self.startofbody)
592 encoding = self.getencoding()
593 if not decode or encoding in ('7bit', '8bit', 'binary'):
594 return self.fp.read()
595 from StringIO import StringIO
596 output = StringIO()
597 mimetools.decode(self.fp, output, encoding)
598 return output.getvalue()
599
600 # Only for multipart messages: return the message's body as a
601 # list of SubMessage objects. Each submessage object behaves
602 # (almost) as a Message object.
603 def getbodyparts(self):
604 if self.getmaintype() != 'multipart':
605 raise Error, \
606 'Content-Type is not multipart/*'
607 bdry = self.getparam('boundary')
608 if not bdry:
609 raise Error, 'multipart/* without boundary param'
610 self.fp.seek(self.startofbody)
611 mf = multifile.MultiFile(self.fp)
612 mf.push(bdry)
613 parts = []
614 while mf.next():
615 n = str(self.number) + '.' + `1 + len(parts)`
616 part = SubMessage(self.folder, n, mf)
617 parts.append(part)
618 mf.pop()
619 return parts
620
621 # Return body, either a string or a list of messages
622 def getbody(self):
623 if self.getmaintype() == 'multipart':
624 return self.getbodyparts()
625 else:
626 return self.getbodytext()
627
628
629class SubMessage(Message):
630
631 # Constructor
632 def __init__(self, f, n, fp):
633 Message.__init__(self, f, n, fp)
634 if self.getmaintype() == 'multipart':
635 self.body = Message.getbodyparts(self)
636 else:
637 self.body = Message.getbodytext(self)
638 # XXX If this is big, should remember file pointers
639
640 # String representation
641 def __repr__(self):
642 f, n, fp = self.folder, self.number, self.fp
643 return 'SubMessage(%s, %s, %s)' % (f, n, fp)
644
645 def getbodytext(self):
646 if type(self.body) == type(''):
647 return self.body
648
649 def getbodyparts(self):
650 if type(self.body) == type([]):
651 return self.body
652
653 def getbody(self):
654 return self.body
655
656
657# Class implementing sets of integers.
658#
659# This is an efficient representation for sets consisting of several
660# continuous ranges, e.g. 1-100,200-400,402-1000 is represented
661# internally as a list of three pairs: [(1,100), (200,400),
662# (402,1000)]. The internal representation is always kept normalized.
663#
664# The constructor has up to three arguments:
665# - the string used to initialize the set (default ''),
666# - the separator between ranges (default ',')
667# - the separator between begin and end of a range (default '-')
668# The separators may be regular expressions and should be different.
669#
670# The tostring() function yields a string that can be passed to another
671# IntSet constructor; __repr__() is a valid IntSet constructor itself.
672#
673# XXX The default begin/end separator means that negative numbers are
674# not supported very well.
675#
676# XXX There are currently no operations to remove set elements.
677
678class IntSet:
679
680 def __init__(self, data = None, sep = ',', rng = '-'):
681 self.pairs = []
682 self.sep = sep
683 self.rng = rng
684 if data: self.fromstring(data)
685
686 def reset(self):
687 self.pairs = []
688
689 def __cmp__(self, other):
690 return cmp(self.pairs, other.pairs)
691
692 def __hash__(self):
693 return hash(self.pairs)
694
695 def __repr__(self):
696 return 'IntSet(%s, %s, %s)' % (`self.tostring()`,
697 `self.sep`, `self.rng`)
698
699 def normalize(self):
700 self.pairs.sort()
701 i = 1
702 while i < len(self.pairs):
703 alo, ahi = self.pairs[i-1]
704 blo, bhi = self.pairs[i]
705 if ahi >= blo-1:
706 self.pairs[i-1:i+1] = [
707 (alo, max(ahi, bhi))]
708 else:
709 i = i+1
710
711 def tostring(self):
712 s = ''
713 for lo, hi in self.pairs:
714 if lo == hi: t = `lo`
715 else: t = `lo` + self.rng + `hi`
716 if s: s = s + (self.sep + t)
717 else: s = t
718 return s
719
720 def tolist(self):
721 l = []
722 for lo, hi in self.pairs:
723 m = range(lo, hi+1)
724 l = l + m
725 return l
726
727 def fromlist(self, list):
728 for i in list:
729 self.append(i)
730
731 def clone(self):
732 new = IntSet()
733 new.pairs = self.pairs[:]
734 return new
735
736 def min(self):
737 return self.pairs[0][0]
738
739 def max(self):
740 return self.pairs[-1][-1]
741
742 def contains(self, x):
743 for lo, hi in self.pairs:
744 if lo <= x <= hi: return 1
745 return 0
746
747 def append(self, x):
748 for i in range(len(self.pairs)):
749 lo, hi = self.pairs[i]
750 if x < lo: # Need to insert before
751 if x+1 == lo:
752 self.pairs[i] = (x, hi)
753 else:
754 self.pairs.insert(i, (x, x))
755 if i > 0 and x-1 == self.pairs[i-1][1]:
756 # Merge with previous
757 self.pairs[i-1:i+1] = [
758 (self.pairs[i-1][0],
759 self.pairs[i][1])
760 ]
761 return
762 if x <= hi: # Already in set
763 return
764 i = len(self.pairs) - 1
765 if i >= 0:
766 lo, hi = self.pairs[i]
767 if x-1 == hi:
768 self.pairs[i] = lo, x
769 return
770 self.pairs.append((x, x))
771
772 def addpair(self, xlo, xhi):
773 if xlo > xhi: return
774 self.pairs.append((xlo, xhi))
775 self.normalize()
776
777 def fromstring(self, data):
778 import string, regsub
779 new = []
780 for part in regsub.split(data, self.sep):
781 list = []
782 for subp in regsub.split(part, self.rng):
783 s = string.strip(subp)
784 list.append(string.atoi(s))
785 if len(list) == 1:
786 new.append((list[0], list[0]))
787 elif len(list) == 2 and list[0] <= list[1]:
788 new.append((list[0], list[1]))
789 else:
790 raise ValueError, 'bad data passed to IntSet'
791 self.pairs = self.pairs + new
792 self.normalize()
793
794
795# Subroutines to read/write entries in .mh_profile and .mh_sequences
796
797def pickline(file, key, casefold = 1):
798 try:
799 f = open(file, 'r')
800 except IOError:
801 return None
802 pat = key + ':'
803 if casefold:
804 prog = regex.compile(pat, regex.casefold)
805 else:
806 prog = regex.compile(pat)
807 while 1:
808 line = f.readline()
809 if not line: break
Guido van Rossumea8ee1d1995-01-26 00:45:20 +0000810 if prog.match(line) >= 0:
Guido van Rossum56013131994-06-23 12:06:02 +0000811 text = line[len(key)+1:]
812 while 1:
813 line = f.readline()
814 if not line or \
815 line[0] not in string.whitespace:
816 break
817 text = text + line
818 return string.strip(text)
819 return None
820
821def updateline(file, key, value, casefold = 1):
822 try:
823 f = open(file, 'r')
824 lines = f.readlines()
825 f.close()
826 except IOError:
827 lines = []
828 pat = key + ':\(.*\)\n'
829 if casefold:
830 prog = regex.compile(pat, regex.casefold)
831 else:
832 prog = regex.compile(pat)
833 if value is None:
834 newline = None
835 else:
Guido van Rossum508a0921996-05-28 22:59:37 +0000836 newline = '%s: %s\n' % (key, value)
Guido van Rossum56013131994-06-23 12:06:02 +0000837 for i in range(len(lines)):
838 line = lines[i]
839 if prog.match(line) == len(line):
840 if newline is None:
841 del lines[i]
842 else:
843 lines[i] = newline
844 break
845 else:
846 if newline is not None:
847 lines.append(newline)
Guido van Rossum508a0921996-05-28 22:59:37 +0000848 tempfile = file + "~"
Guido van Rossum56013131994-06-23 12:06:02 +0000849 f = open(tempfile, 'w')
850 for line in lines:
851 f.write(line)
852 f.close()
Guido van Rossum508a0921996-05-28 22:59:37 +0000853 os.rename(tempfile, file)
Guido van Rossum56013131994-06-23 12:06:02 +0000854
855
856# Test program
857
858def test():
859 global mh, f
860 os.system('rm -rf $HOME/Mail/@test')
861 mh = MH()
862 def do(s): print s; print eval(s)
863 do('mh.listfolders()')
864 do('mh.listallfolders()')
865 testfolders = ['@test', '@test/test1', '@test/test2',
866 '@test/test1/test11', '@test/test1/test12',
867 '@test/test1/test11/test111']
868 for t in testfolders: do('mh.makefolder(%s)' % `t`)
869 do('mh.listsubfolders(\'@test\')')
870 do('mh.listallsubfolders(\'@test\')')
871 f = mh.openfolder('@test')
872 do('f.listsubfolders()')
873 do('f.listallsubfolders()')
874 do('f.getsequences()')
875 seqs = f.getsequences()
876 seqs['foo'] = IntSet('1-10 12-20', ' ').tolist()
877 print seqs
878 f.putsequences(seqs)
879 do('f.getsequences()')
880 testfolders.reverse()
881 for t in testfolders: do('mh.deletefolder(%s)' % `t`)
882 do('mh.getcontext()')
883 context = mh.getcontext()
884 f = mh.openfolder(context)
885 do('f.listmessages()')
886 do('f.getcurrent()')
887
888
889if __name__ == '__main__':
890 test()