desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return a list of messages. Memory intensive.'
def values(self):
return list(self.itervalues())
'Return an iterator over (key, message) tuples.'
def iteritems(self):
for key in self.iterkeys(): try: value = self[key] except KeyError: continue (yield (key, value))
'Return a list of (key, message) tuples. Memory intensive.'
def items(self):
return list(self.iteritems())
'Return True if the keyed message exists, False otherwise.'
def has_key(self, key):
raise NotImplementedError('Method must be implemented by subclass')
'Return a count of messages in the mailbox.'
def __len__(self):
raise NotImplementedError('Method must be implemented by subclass')
'Delete all messages.'
def clear(self):
for key in self.iterkeys(): self.discard(key)
'Delete the keyed message and return it, or default.'
def pop(self, key, default=None):
try: result = self[key] except KeyError: return default self.discard(key) return result
'Delete an arbitrary (key, message) pair and return it.'
def popitem(self):
for key in self.iterkeys(): return (key, self.pop(key)) else: raise KeyError('No messages in mailbox')
'Change the messages that correspond to certain keys.'
def update(self, arg=None):
if hasattr(arg, 'iteritems'): source = arg.iteritems() elif hasattr(arg, 'items'): source = arg.items() else: source = arg bad_key = False for (key, message) in source: try: self[key] = message except KeyError: bad_key = True if bad...
'Write any pending changes to the disk.'
def flush(self):
raise NotImplementedError('Method must be implemented by subclass')
'Lock the mailbox.'
def lock(self):
raise NotImplementedError('Method must be implemented by subclass')
'Unlock the mailbox if it is locked.'
def unlock(self):
raise NotImplementedError('Method must be implemented by subclass')
'Flush and close the mailbox.'
def close(self):
raise NotImplementedError('Method must be implemented by subclass')
'Dump message contents to target file.'
def _dump_message(self, message, target, mangle_from_=False):
if isinstance(message, email.message.Message): buffer = StringIO.StringIO() gen = email.generator.Generator(buffer, mangle_from_, 0) gen.flatten(message) buffer.seek(0) data = buffer.read().replace('\n', os.linesep) target.write(data) if (self._append_newline ...
'Initialize a Maildir instance.'
def __init__(self, dirname, factory=rfc822.Message, create=True):
Mailbox.__init__(self, dirname, factory, create) self._paths = {'tmp': os.path.join(self._path, 'tmp'), 'new': os.path.join(self._path, 'new'), 'cur': os.path.join(self._path, 'cur')} if (not os.path.exists(self._path)): if create: os.mkdir(self._path, 448) for path in self._...
'Add message and return assigned key.'
def add(self, message):
tmp_file = self._create_tmp() try: self._dump_message(message, tmp_file) except BaseException: tmp_file.close() os.remove(tmp_file.name) raise _sync_close(tmp_file) if isinstance(message, MaildirMessage): subdir = message.get_subdir() suffix = (self.co...
'Remove the keyed message; raise KeyError if it doesn\'t exist.'
def remove(self, key):
os.remove(os.path.join(self._path, self._lookup(key)))
'If the keyed message exists, remove it.'
def discard(self, key):
try: self.remove(key) except KeyError: pass except OSError as e: if (e.errno != errno.ENOENT): raise
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
def __setitem__(self, key, message):
old_subpath = self._lookup(key) temp_key = self.add(message) temp_subpath = self._lookup(temp_key) if isinstance(message, MaildirMessage): dominant_subpath = temp_subpath else: dominant_subpath = old_subpath subdir = os.path.dirname(dominant_subpath) if (self.colon in dominan...
'Return a Message representation or raise a KeyError.'
def get_message(self, key):
subpath = self._lookup(key) f = open(os.path.join(self._path, subpath), 'r') try: if self._factory: msg = self._factory(f) else: msg = MaildirMessage(f) finally: f.close() (subdir, name) = os.path.split(subpath) msg.set_subdir(subdir) if (self....
'Return a string representation or raise a KeyError.'
def get_string(self, key):
f = open(os.path.join(self._path, self._lookup(key)), 'r') try: return f.read() finally: f.close()
'Return a file-like representation or raise a KeyError.'
def get_file(self, key):
f = open(os.path.join(self._path, self._lookup(key)), 'rb') return _ProxyFile(f)
'Return an iterator over keys.'
def iterkeys(self):
self._refresh() for key in self._toc: try: self._lookup(key) except KeyError: continue (yield key)
'Return True if the keyed message exists, False otherwise.'
def has_key(self, key):
self._refresh() return (key in self._toc)
'Return a count of messages in the mailbox.'
def __len__(self):
self._refresh() return len(self._toc)
'Write any pending changes to disk.'
def flush(self):
pass
'Lock the mailbox.'
def lock(self):
return
'Unlock the mailbox if it is locked.'
def unlock(self):
return
'Flush and close the mailbox.'
def close(self):
return
'Return a list of folder names.'
def list_folders(self):
result = [] for entry in os.listdir(self._path): if ((len(entry) > 1) and (entry[0] == '.') and os.path.isdir(os.path.join(self._path, entry))): result.append(entry[1:]) return result
'Return a Maildir instance for the named folder.'
def get_folder(self, folder):
return Maildir(os.path.join(self._path, ('.' + folder)), factory=self._factory, create=False)
'Create a folder and return a Maildir instance representing it.'
def add_folder(self, folder):
path = os.path.join(self._path, ('.' + folder)) result = Maildir(path, factory=self._factory) maildirfolder_path = os.path.join(path, 'maildirfolder') if (not os.path.exists(maildirfolder_path)): os.close(os.open(maildirfolder_path, (os.O_CREAT | os.O_WRONLY), 438)) return result
'Delete the named folder, which must be empty.'
def remove_folder(self, folder):
path = os.path.join(self._path, ('.' + folder)) for entry in (os.listdir(os.path.join(path, 'new')) + os.listdir(os.path.join(path, 'cur'))): if ((len(entry) < 1) or (entry[0] != '.')): raise NotEmptyError(('Folder contains message(s): %s' % folder)) for entry in os.listdir(path...
'Delete old files in "tmp".'
def clean(self):
now = time.time() for entry in os.listdir(os.path.join(self._path, 'tmp')): path = os.path.join(self._path, 'tmp', entry) if ((now - os.path.getatime(path)) > 129600): os.remove(path)
'Create a file in the tmp subdirectory and open and return it.'
def _create_tmp(self):
now = time.time() hostname = socket.gethostname() if ('/' in hostname): hostname = hostname.replace('/', '\\057') if (':' in hostname): hostname = hostname.replace(':', '\\072') uniq = ('%s.M%sP%sQ%s.%s' % (int(now), int(((now % 1) * 1000000.0)), os.getpid(), Maildir._count, hostname...
'Update table of contents mapping.'
def _refresh(self):
if ((time.time() - self._last_read) > (2 + self._skewfactor)): refresh = False for subdir in self._toc_mtimes: mtime = os.path.getmtime(self._paths[subdir]) if (mtime > self._toc_mtimes[subdir]): refresh = True self._toc_mtimes[subdir] = mtime ...
'Use TOC to return subpath for given key, or raise a KeyError.'
def _lookup(self, key):
try: if os.path.exists(os.path.join(self._path, self._toc[key])): return self._toc[key] except KeyError: pass self._refresh() try: return self._toc[key] except KeyError: raise KeyError(('No message with key: %s' % key))
'Return the next message in a one-time iteration.'
def next(self):
if (not hasattr(self, '_onetime_keys')): self._onetime_keys = self.iterkeys() while True: try: return self[self._onetime_keys.next()] except StopIteration: return None except KeyError: continue
'Initialize a single-file mailbox.'
def __init__(self, path, factory=None, create=True):
Mailbox.__init__(self, path, factory, create) try: f = open(self._path, 'rb+') except IOError as e: if (e.errno == errno.ENOENT): if create: f = open(self._path, 'wb+') else: raise NoSuchMailboxError(self._path) elif (e.errno in...
'Add message and return assigned key.'
def add(self, message):
self._lookup() self._toc[self._next_key] = self._append_message(message) self._next_key += 1 self._pending_sync = True return (self._next_key - 1)
'Remove the keyed message; raise KeyError if it doesn\'t exist.'
def remove(self, key):
self._lookup(key) del self._toc[key] self._pending = True
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
def __setitem__(self, key, message):
self._lookup(key) self._toc[key] = self._append_message(message) self._pending = True
'Return an iterator over keys.'
def iterkeys(self):
self._lookup() for key in self._toc.keys(): (yield key)
'Return True if the keyed message exists, False otherwise.'
def has_key(self, key):
self._lookup() return (key in self._toc)
'Return a count of messages in the mailbox.'
def __len__(self):
self._lookup() return len(self._toc)
'Lock the mailbox.'
def lock(self):
if (not self._locked): _lock_file(self._file) self._locked = True
'Unlock the mailbox if it is locked.'
def unlock(self):
if self._locked: _unlock_file(self._file) self._locked = False
'Write any pending changes to disk.'
def flush(self):
if (not self._pending): if self._pending_sync: _sync_flush(self._file) self._pending_sync = False return assert (self._toc is not None) self._file.seek(0, 2) cur_len = self._file.tell() if (cur_len != self._file_length): raise ExternalClashError(('Size...
'Called before writing the mailbox to file f.'
def _pre_mailbox_hook(self, f):
return
'Called before writing each message to file f.'
def _pre_message_hook(self, f):
return
'Called after writing each message to file f.'
def _post_message_hook(self, f):
return
'Flush and close the mailbox.'
def close(self):
try: self.flush() finally: try: if self._locked: self.unlock() finally: self._file.close()
'Return (start, stop) or raise KeyError.'
def _lookup(self, key=None):
if (self._toc is None): self._generate_toc() if (key is not None): try: return self._toc[key] except KeyError: raise KeyError(('No message with key: %s' % key))
'Append message to mailbox and return (start, stop) offsets.'
def _append_message(self, message):
self._file.seek(0, 2) before = self._file.tell() if ((len(self._toc) == 0) and (not self._pending)): self._pre_mailbox_hook(self._file) try: self._pre_message_hook(self._file) offsets = self._install_message(message) self._post_message_hook(self._file) except BaseExce...
'Return a Message representation or raise a KeyError.'
def get_message(self, key):
(start, stop) = self._lookup(key) self._file.seek(start) from_line = self._file.readline().replace(os.linesep, '') string = self._file.read((stop - self._file.tell())) msg = self._message_factory(string.replace(os.linesep, '\n')) msg.set_from(from_line[5:]) return msg
'Return a string representation or raise a KeyError.'
def get_string(self, key, from_=False):
(start, stop) = self._lookup(key) self._file.seek(start) if (not from_): self._file.readline() string = self._file.read((stop - self._file.tell())) return string.replace(os.linesep, '\n')
'Return a file-like representation or raise a KeyError.'
def get_file(self, key, from_=False):
(start, stop) = self._lookup(key) self._file.seek(start) if (not from_): self._file.readline() return _PartialFile(self._file, self._file.tell(), stop)
'Format a message and blindly write to self._file.'
def _install_message(self, message):
from_line = None if (isinstance(message, str) and message.startswith('From ')): newline = message.find('\n') if (newline != (-1)): from_line = message[:newline] message = message[(newline + 1):] else: from_line = message message = '' ...
'Initialize an mbox mailbox.'
def __init__(self, path, factory=None, create=True):
self._message_factory = mboxMessage _mboxMMDF.__init__(self, path, factory, create)
'Called after writing each message to file f.'
def _post_message_hook(self, f):
f.write(os.linesep)
'Generate key-to-(start, stop) table of contents.'
def _generate_toc(self):
(starts, stops) = ([], []) last_was_empty = False self._file.seek(0) while True: line_pos = self._file.tell() line = self._file.readline() if line.startswith('From '): if (len(stops) < len(starts)): if last_was_empty: stops.appen...
'Initialize an MMDF mailbox.'
def __init__(self, path, factory=None, create=True):
self._message_factory = MMDFMessage _mboxMMDF.__init__(self, path, factory, create)
'Called before writing each message to file f.'
def _pre_message_hook(self, f):
f.write(('\x01\x01\x01\x01' + os.linesep))
'Called after writing each message to file f.'
def _post_message_hook(self, f):
f.write(((os.linesep + '\x01\x01\x01\x01') + os.linesep))
'Generate key-to-(start, stop) table of contents.'
def _generate_toc(self):
(starts, stops) = ([], []) self._file.seek(0) next_pos = 0 while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line.startswith(('\x01\x01\x01\x01' + os.linesep)): starts.append(next_pos) while True: ...
'Initialize an MH instance.'
def __init__(self, path, factory=None, create=True):
Mailbox.__init__(self, path, factory, create) if (not os.path.exists(self._path)): if create: os.mkdir(self._path, 448) os.close(os.open(os.path.join(self._path, '.mh_sequences'), ((os.O_CREAT | os.O_EXCL) | os.O_WRONLY), 384)) else: raise NoSuchMailboxError(s...
'Add message and return assigned key.'
def add(self, message):
keys = self.keys() if (len(keys) == 0): new_key = 1 else: new_key = (max(keys) + 1) new_path = os.path.join(self._path, str(new_key)) f = _create_carefully(new_path) closed = False try: if self._locked: _lock_file(f) try: try: ...
'Remove the keyed message; raise KeyError if it doesn\'t exist.'
def remove(self, key):
path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except IOError as e: if (e.errno == errno.ENOENT): raise KeyError(('No message with key: %s' % key)) else: raise else: f.close() os.remove(path)
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
def __setitem__(self, key, message):
path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except IOError as e: if (e.errno == errno.ENOENT): raise KeyError(('No message with key: %s' % key)) else: raise try: if self._locked: _lock_file(f) ...
'Return a Message representation or raise a KeyError.'
def get_message(self, key):
try: if self._locked: f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') except IOError as e: if (e.errno == errno.ENOENT): raise KeyError(('No message with key: %s' % key)) el...
'Return a string representation or raise a KeyError.'
def get_string(self, key):
try: if self._locked: f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') except IOError as e: if (e.errno == errno.ENOENT): raise KeyError(('No message with key: %s' % key)) el...
'Return a file-like representation or raise a KeyError.'
def get_file(self, key):
try: f = open(os.path.join(self._path, str(key)), 'rb') except IOError as e: if (e.errno == errno.ENOENT): raise KeyError(('No message with key: %s' % key)) else: raise return _ProxyFile(f)
'Return an iterator over keys.'
def iterkeys(self):
return iter(sorted((int(entry) for entry in os.listdir(self._path) if entry.isdigit())))
'Return True if the keyed message exists, False otherwise.'
def has_key(self, key):
return os.path.exists(os.path.join(self._path, str(key)))
'Return a count of messages in the mailbox.'
def __len__(self):
return len(list(self.iterkeys()))
'Lock the mailbox.'
def lock(self):
if (not self._locked): self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+') _lock_file(self._file) self._locked = True
'Unlock the mailbox if it is locked.'
def unlock(self):
if self._locked: _unlock_file(self._file) _sync_close(self._file) del self._file self._locked = False
'Write any pending changes to the disk.'
def flush(self):
return
'Flush and close the mailbox.'
def close(self):
if self._locked: self.unlock()
'Return a list of folder names.'
def list_folders(self):
result = [] for entry in os.listdir(self._path): if os.path.isdir(os.path.join(self._path, entry)): result.append(entry) return result
'Return an MH instance for the named folder.'
def get_folder(self, folder):
return MH(os.path.join(self._path, folder), factory=self._factory, create=False)
'Create a folder and return an MH instance representing it.'
def add_folder(self, folder):
return MH(os.path.join(self._path, folder), factory=self._factory)
'Delete the named folder, which must be empty.'
def remove_folder(self, folder):
path = os.path.join(self._path, folder) entries = os.listdir(path) if (entries == ['.mh_sequences']): os.remove(os.path.join(path, '.mh_sequences')) elif (entries == []): pass else: raise NotEmptyError(('Folder not empty: %s' % self._path)) os.rmdir(path)
'Return a name-to-key-list dictionary to define each sequence.'
def get_sequences(self):
results = {} f = open(os.path.join(self._path, '.mh_sequences'), 'r') try: all_keys = set(self.keys()) for line in f: try: (name, contents) = line.split(':') keys = set() for spec in contents.split(): if spec.isd...
'Set sequences using the given name-to-key-list dictionary.'
def set_sequences(self, sequences):
f = open(os.path.join(self._path, '.mh_sequences'), 'r+') try: os.close(os.open(f.name, (os.O_WRONLY | os.O_TRUNC))) for (name, keys) in sequences.iteritems(): if (len(keys) == 0): continue f.write(('%s:' % name)) prev = None comple...
'Re-name messages to eliminate numbering gaps. Invalidates keys.'
def pack(self):
sequences = self.get_sequences() prev = 0 changes = [] for key in self.iterkeys(): if ((key - 1) != prev): changes.append((key, (prev + 1))) if hasattr(os, 'link'): os.link(os.path.join(self._path, str(key)), os.path.join(self._path, str((prev + 1)))) ...
'Inspect a new MHMessage and update sequences appropriately.'
def _dump_sequences(self, message, key):
pending_sequences = message.get_sequences() all_sequences = self.get_sequences() for (name, key_list) in all_sequences.iteritems(): if (name in pending_sequences): key_list.append(key) elif (key in key_list): del key_list[key_list.index(key)] for sequence in pendi...
'Initialize a Babyl mailbox.'
def __init__(self, path, factory=None, create=True):
_singlefileMailbox.__init__(self, path, factory, create) self._labels = {}
'Add message and return assigned key.'
def add(self, message):
key = _singlefileMailbox.add(self, message) if isinstance(message, BabylMessage): self._labels[key] = message.get_labels() return key
'Remove the keyed message; raise KeyError if it doesn\'t exist.'
def remove(self, key):
_singlefileMailbox.remove(self, key) if (key in self._labels): del self._labels[key]
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
def __setitem__(self, key, message):
_singlefileMailbox.__setitem__(self, key, message) if isinstance(message, BabylMessage): self._labels[key] = message.get_labels()
'Return a Message representation or raise a KeyError.'
def get_message(self, key):
(start, stop) = self._lookup(key) self._file.seek(start) self._file.readline() original_headers = StringIO.StringIO() while True: line = self._file.readline() if ((line == ('*** EOOH ***' + os.linesep)) or (line == '')): break original_headers.write(line.rep...
'Return a string representation or raise a KeyError.'
def get_string(self, key):
(start, stop) = self._lookup(key) self._file.seek(start) self._file.readline() original_headers = StringIO.StringIO() while True: line = self._file.readline() if ((line == ('*** EOOH ***' + os.linesep)) or (line == '')): break original_headers.write(line.rep...
'Return a file-like representation or raise a KeyError.'
def get_file(self, key):
return StringIO.StringIO(self.get_string(key).replace('\n', os.linesep))
'Return a list of user-defined labels in the mailbox.'
def get_labels(self):
self._lookup() labels = set() for label_list in self._labels.values(): labels.update(label_list) labels.difference_update(self._special_labels) return list(labels)
'Generate key-to-(start, stop) table of contents.'
def _generate_toc(self):
(starts, stops) = ([], []) self._file.seek(0) next_pos = 0 label_lists = [] while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if (line == ('\x1f\x0c' + os.linesep)): if (len(stops) < len(starts)): sto...
'Called before writing the mailbox to file f.'
def _pre_mailbox_hook(self, f):
f.write(('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\x1f' % (os.linesep, os.linesep, ','.join(self.get_labels()), os.linesep)))
'Called before writing each message to file f.'
def _pre_message_hook(self, f):
f.write(('\x0c' + os.linesep))
'Called after writing each message to file f.'
def _post_message_hook(self, f):
f.write((os.linesep + '\x1f'))
'Write message contents and return (start, stop).'
def _install_message(self, message):
start = self._file.tell() if isinstance(message, BabylMessage): special_labels = [] labels = [] for label in message.get_labels(): if (label in self._special_labels): special_labels.append(label) else: labels.append(label) s...