blob: dd387626225a67bfb36b1a6178b9e6306be7dab0 [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)
Guido van Rossum3508d601996-11-12 04:15:47 +0000525 # -- but not from 'cur'!!!
Guido van Rossum56013131994-06-23 12:06:02 +0000526 def removefromallsequences(self, list):
527 if hasattr(self, 'last') and self.last in list:
528 del self.last
529 sequences = self.getsequences()
530 changed = 0
531 for name, seq in sequences.items():
Guido van Rossum3508d601996-11-12 04:15:47 +0000532 if name == 'cur':
533 continue
Guido van Rossum56013131994-06-23 12:06:02 +0000534 for n in list:
535 if n in seq:
536 seq.remove(n)
537 changed = 1
538 if not seq:
539 del sequences[name]
540 if changed:
Guido van Rossum5f47e571994-07-14 14:01:00 +0000541 self.putsequences(sequences)
Guido van Rossum56013131994-06-23 12:06:02 +0000542
543 # Return the last message number
544 def getlast(self):
545 if not hasattr(self, 'last'):
546 messages = self.listmessages()
547 return self.last
548
549 # Set the last message number
550 def setlast(self, last):
551 if last is None:
552 if hasattr(self, 'last'):
553 del self.last
554 else:
555 self.last = last
556
557class Message(mimetools.Message):
558
559 # Constructor
560 def __init__(self, f, n, fp = None):
561 self.folder = f
562 self.number = n
563 if not fp:
564 path = f.getmessagefilename(n)
565 fp = open(path, 'r')
566 mimetools.Message.__init__(self, fp)
567
568 # String representation
569 def __repr__(self):
570 return 'Message(%s, %s)' % (repr(self.folder), self.number)
571
572 # Return the message's header text as a string. If an
573 # argument is specified, it is used as a filter predicate to
574 # decide which headers to return (its argument is the header
575 # name converted to lower case).
576 def getheadertext(self, pred = None):
577 if not pred:
578 return string.joinfields(self.headers, '')
579 headers = []
580 hit = 0
581 for line in self.headers:
582 if line[0] not in string.whitespace:
583 i = string.find(line, ':')
584 if i > 0:
585 hit = pred(string.lower(line[:i]))
586 if hit: headers.append(line)
587 return string.joinfields(headers, '')
588
589 # Return the message's body text as string. This undoes a
590 # Content-Transfer-Encoding, but does not interpret other MIME
591 # features (e.g. multipart messages). To suppress to
592 # decoding, pass a 0 as argument
593 def getbodytext(self, decode = 1):
594 self.fp.seek(self.startofbody)
595 encoding = self.getencoding()
596 if not decode or encoding in ('7bit', '8bit', 'binary'):
597 return self.fp.read()
598 from StringIO import StringIO
599 output = StringIO()
600 mimetools.decode(self.fp, output, encoding)
601 return output.getvalue()
602
603 # Only for multipart messages: return the message's body as a
604 # list of SubMessage objects. Each submessage object behaves
605 # (almost) as a Message object.
606 def getbodyparts(self):
607 if self.getmaintype() != 'multipart':
608 raise Error, \
609 'Content-Type is not multipart/*'
610 bdry = self.getparam('boundary')
611 if not bdry:
612 raise Error, 'multipart/* without boundary param'
613 self.fp.seek(self.startofbody)
614 mf = multifile.MultiFile(self.fp)
615 mf.push(bdry)
616 parts = []
617 while mf.next():
618 n = str(self.number) + '.' + `1 + len(parts)`
619 part = SubMessage(self.folder, n, mf)
620 parts.append(part)
621 mf.pop()
622 return parts
623
624 # Return body, either a string or a list of messages
625 def getbody(self):
626 if self.getmaintype() == 'multipart':
627 return self.getbodyparts()
628 else:
629 return self.getbodytext()
630
631
632class SubMessage(Message):
633
634 # Constructor
635 def __init__(self, f, n, fp):
636 Message.__init__(self, f, n, fp)
637 if self.getmaintype() == 'multipart':
638 self.body = Message.getbodyparts(self)
639 else:
640 self.body = Message.getbodytext(self)
641 # XXX If this is big, should remember file pointers
642
643 # String representation
644 def __repr__(self):
645 f, n, fp = self.folder, self.number, self.fp
646 return 'SubMessage(%s, %s, %s)' % (f, n, fp)
647
648 def getbodytext(self):
649 if type(self.body) == type(''):
650 return self.body
651
652 def getbodyparts(self):
653 if type(self.body) == type([]):
654 return self.body
655
656 def getbody(self):
657 return self.body
658
659
660# Class implementing sets of integers.
661#
662# This is an efficient representation for sets consisting of several
663# continuous ranges, e.g. 1-100,200-400,402-1000 is represented
664# internally as a list of three pairs: [(1,100), (200,400),
665# (402,1000)]. The internal representation is always kept normalized.
666#
667# The constructor has up to three arguments:
668# - the string used to initialize the set (default ''),
669# - the separator between ranges (default ',')
670# - the separator between begin and end of a range (default '-')
671# The separators may be regular expressions and should be different.
672#
673# The tostring() function yields a string that can be passed to another
674# IntSet constructor; __repr__() is a valid IntSet constructor itself.
675#
676# XXX The default begin/end separator means that negative numbers are
677# not supported very well.
678#
679# XXX There are currently no operations to remove set elements.
680
681class IntSet:
682
683 def __init__(self, data = None, sep = ',', rng = '-'):
684 self.pairs = []
685 self.sep = sep
686 self.rng = rng
687 if data: self.fromstring(data)
688
689 def reset(self):
690 self.pairs = []
691
692 def __cmp__(self, other):
693 return cmp(self.pairs, other.pairs)
694
695 def __hash__(self):
696 return hash(self.pairs)
697
698 def __repr__(self):
699 return 'IntSet(%s, %s, %s)' % (`self.tostring()`,
700 `self.sep`, `self.rng`)
701
702 def normalize(self):
703 self.pairs.sort()
704 i = 1
705 while i < len(self.pairs):
706 alo, ahi = self.pairs[i-1]
707 blo, bhi = self.pairs[i]
708 if ahi >= blo-1:
709 self.pairs[i-1:i+1] = [
710 (alo, max(ahi, bhi))]
711 else:
712 i = i+1
713
714 def tostring(self):
715 s = ''
716 for lo, hi in self.pairs:
717 if lo == hi: t = `lo`
718 else: t = `lo` + self.rng + `hi`
719 if s: s = s + (self.sep + t)
720 else: s = t
721 return s
722
723 def tolist(self):
724 l = []
725 for lo, hi in self.pairs:
726 m = range(lo, hi+1)
727 l = l + m
728 return l
729
730 def fromlist(self, list):
731 for i in list:
732 self.append(i)
733
734 def clone(self):
735 new = IntSet()
736 new.pairs = self.pairs[:]
737 return new
738
739 def min(self):
740 return self.pairs[0][0]
741
742 def max(self):
743 return self.pairs[-1][-1]
744
745 def contains(self, x):
746 for lo, hi in self.pairs:
747 if lo <= x <= hi: return 1
748 return 0
749
750 def append(self, x):
751 for i in range(len(self.pairs)):
752 lo, hi = self.pairs[i]
753 if x < lo: # Need to insert before
754 if x+1 == lo:
755 self.pairs[i] = (x, hi)
756 else:
757 self.pairs.insert(i, (x, x))
758 if i > 0 and x-1 == self.pairs[i-1][1]:
759 # Merge with previous
760 self.pairs[i-1:i+1] = [
761 (self.pairs[i-1][0],
762 self.pairs[i][1])
763 ]
764 return
765 if x <= hi: # Already in set
766 return
767 i = len(self.pairs) - 1
768 if i >= 0:
769 lo, hi = self.pairs[i]
770 if x-1 == hi:
771 self.pairs[i] = lo, x
772 return
773 self.pairs.append((x, x))
774
775 def addpair(self, xlo, xhi):
776 if xlo > xhi: return
777 self.pairs.append((xlo, xhi))
778 self.normalize()
779
780 def fromstring(self, data):
781 import string, regsub
782 new = []
783 for part in regsub.split(data, self.sep):
784 list = []
785 for subp in regsub.split(part, self.rng):
786 s = string.strip(subp)
787 list.append(string.atoi(s))
788 if len(list) == 1:
789 new.append((list[0], list[0]))
790 elif len(list) == 2 and list[0] <= list[1]:
791 new.append((list[0], list[1]))
792 else:
793 raise ValueError, 'bad data passed to IntSet'
794 self.pairs = self.pairs + new
795 self.normalize()
796
797
798# Subroutines to read/write entries in .mh_profile and .mh_sequences
799
800def pickline(file, key, casefold = 1):
801 try:
802 f = open(file, 'r')
803 except IOError:
804 return None
805 pat = key + ':'
806 if casefold:
807 prog = regex.compile(pat, regex.casefold)
808 else:
809 prog = regex.compile(pat)
810 while 1:
811 line = f.readline()
812 if not line: break
Guido van Rossumea8ee1d1995-01-26 00:45:20 +0000813 if prog.match(line) >= 0:
Guido van Rossum56013131994-06-23 12:06:02 +0000814 text = line[len(key)+1:]
815 while 1:
816 line = f.readline()
817 if not line or \
818 line[0] not in string.whitespace:
819 break
820 text = text + line
821 return string.strip(text)
822 return None
823
824def updateline(file, key, value, casefold = 1):
825 try:
826 f = open(file, 'r')
827 lines = f.readlines()
828 f.close()
829 except IOError:
830 lines = []
831 pat = key + ':\(.*\)\n'
832 if casefold:
833 prog = regex.compile(pat, regex.casefold)
834 else:
835 prog = regex.compile(pat)
836 if value is None:
837 newline = None
838 else:
Guido van Rossum508a0921996-05-28 22:59:37 +0000839 newline = '%s: %s\n' % (key, value)
Guido van Rossum56013131994-06-23 12:06:02 +0000840 for i in range(len(lines)):
841 line = lines[i]
842 if prog.match(line) == len(line):
843 if newline is None:
844 del lines[i]
845 else:
846 lines[i] = newline
847 break
848 else:
849 if newline is not None:
850 lines.append(newline)
Guido van Rossum508a0921996-05-28 22:59:37 +0000851 tempfile = file + "~"
Guido van Rossum56013131994-06-23 12:06:02 +0000852 f = open(tempfile, 'w')
853 for line in lines:
854 f.write(line)
855 f.close()
Guido van Rossum508a0921996-05-28 22:59:37 +0000856 os.rename(tempfile, file)
Guido van Rossum56013131994-06-23 12:06:02 +0000857
858
859# Test program
860
861def test():
862 global mh, f
863 os.system('rm -rf $HOME/Mail/@test')
864 mh = MH()
865 def do(s): print s; print eval(s)
866 do('mh.listfolders()')
867 do('mh.listallfolders()')
868 testfolders = ['@test', '@test/test1', '@test/test2',
869 '@test/test1/test11', '@test/test1/test12',
870 '@test/test1/test11/test111']
871 for t in testfolders: do('mh.makefolder(%s)' % `t`)
872 do('mh.listsubfolders(\'@test\')')
873 do('mh.listallsubfolders(\'@test\')')
874 f = mh.openfolder('@test')
875 do('f.listsubfolders()')
876 do('f.listallsubfolders()')
877 do('f.getsequences()')
878 seqs = f.getsequences()
879 seqs['foo'] = IntSet('1-10 12-20', ' ').tolist()
880 print seqs
881 f.putsequences(seqs)
882 do('f.getsequences()')
883 testfolders.reverse()
884 for t in testfolders: do('mh.deletefolder(%s)' % `t`)
885 do('mh.getcontext()')
886 context = mh.getcontext()
887 f = mh.openfolder(context)
888 do('f.listmessages()')
889 do('f.getcurrent()')
890
891
892if __name__ == '__main__':
893 test()