desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Process a NEWNEWS command. Arguments:
- group: group name or \'*\'
- date: string \'yymmdd\' indicating the date
- time: string \'hhmmss\' indicating the time
Return:
- resp: server response if successful
- list: list of message ids'
| def newnews(self, group, date, time, file=None):
| cmd = ((((('NEWNEWS ' + group) + ' ') + date) + ' ') + time)
return self.longcmd(cmd, file)
|
'Process a LIST command. Return:
- resp: server response if successful
- list: list of (group, last, first, flag) (strings)'
| def list(self, file=None):
| (resp, list) = self.longcmd('LIST', file)
for i in range(len(list)):
list[i] = tuple(list[i].split())
return (resp, list)
|
'Get a description for a single group. If more than one
group matches (\'group\' is a pattern), return the first. If no
group matches, return an empty string.
This elides the response code from the server, since it can
only be \'215\' or \'285\' (for xgtitle) anyway. If the response
code is needed, use the \'descrip... | def description(self, group):
| (resp, lines) = self.descriptions(group)
if (len(lines) == 0):
return ''
else:
return lines[0][1]
|
'Get descriptions for a range of groups.'
| def descriptions(self, group_pattern):
| line_pat = re.compile('^(?P<group>[^ DCTB ]+)[ DCTB ]+(.*)$')
(resp, raw_lines) = self.longcmd(('LIST NEWSGROUPS ' + group_pattern))
if (resp[:3] != '215'):
(resp, raw_lines) = self.longcmd(('XGTITLE ' + group_pattern))
lines = []
for raw_line in raw_lines:
match = l... |
'Process a GROUP command. Argument:
- group: the group name
Returns:
- resp: server response if successful
- count: number of articles (string)
- first: first article number (string)
- last: last article number (string)
- name: the group name'
| def group(self, name):
| resp = self.shortcmd(('GROUP ' + name))
if (resp[:3] != '211'):
raise NNTPReplyError(resp)
words = resp.split()
count = first = last = 0
n = len(words)
if (n > 1):
count = words[1]
if (n > 2):
first = words[2]
if (n > 3):
last = ... |
'Process a HELP command. Returns:
- resp: server response if successful
- list: list of strings'
| def help(self, file=None):
| return self.longcmd('HELP', file)
|
'Internal: parse the response of a STAT, NEXT or LAST command.'
| def statparse(self, resp):
| if (resp[:2] != '22'):
raise NNTPReplyError(resp)
words = resp.split()
nr = 0
id = ''
n = len(words)
if (n > 1):
nr = words[1]
if (n > 2):
id = words[2]
return (resp, nr, id)
|
'Internal: process a STAT, NEXT or LAST command.'
| def statcmd(self, line):
| resp = self.shortcmd(line)
return self.statparse(resp)
|
'Process a STAT command. Argument:
- id: article number or message id
Returns:
- resp: server response if successful
- nr: the article number
- id: the message id'
| def stat(self, id):
| return self.statcmd(('STAT ' + id))
|
'Process a NEXT command. No arguments. Return as for STAT.'
| def next(self):
| return self.statcmd('NEXT')
|
'Process a LAST command. No arguments. Return as for STAT.'
| def last(self):
| return self.statcmd('LAST')
|
'Internal: process a HEAD, BODY or ARTICLE command.'
| def artcmd(self, line, file=None):
| (resp, list) = self.longcmd(line, file)
(resp, nr, id) = self.statparse(resp)
return (resp, nr, id, list)
|
'Process a HEAD command. Argument:
- id: article number or message id
Returns:
- resp: server response if successful
- nr: article number
- id: message id
- list: the lines of the article\'s header'
| def head(self, id):
| return self.artcmd(('HEAD ' + id))
|
'Process a BODY command. Argument:
- id: article number or message id
- file: Filename string or file object to store the article in
Returns:
- resp: server response if successful
- nr: article number
- id: message id
- list: the lines of the article\'s body or an empty list
if file was used'
| def body(self, id, file=None):
| return self.artcmd(('BODY ' + id), file)
|
'Process an ARTICLE command. Argument:
- id: article number or message id
Returns:
- resp: server response if successful
- nr: article number
- id: message id
- list: the lines of the article'
| def article(self, id):
| return self.artcmd(('ARTICLE ' + id))
|
'Process a SLAVE command. Returns:
- resp: server response if successful'
| def slave(self):
| return self.shortcmd('SLAVE')
|
'Process an XHDR command (optional server extension). Arguments:
- hdr: the header type (e.g. \'subject\')
- str: an article nr, a message id, or a range nr1-nr2
Returns:
- resp: server response if successful
- list: list of (nr, value) strings'
| def xhdr(self, hdr, str, file=None):
| pat = re.compile('^([0-9]+) ?(.*)\n?')
(resp, lines) = self.longcmd(((('XHDR ' + hdr) + ' ') + str), file)
for i in range(len(lines)):
line = lines[i]
m = pat.match(line)
if m:
lines[i] = m.group(1, 2)
return (resp, lines)
|
'Process an XOVER command (optional server extension) Arguments:
- start: start of range
- end: end of range
Returns:
- resp: server response if successful
- list: list of (art-nr, subject, poster, date,
id, references, size, lines)'
| def xover(self, start, end, file=None):
| (resp, lines) = self.longcmd(((('XOVER ' + start) + '-') + end), file)
xover_lines = []
for line in lines:
elem = line.split(' DCTB ')
try:
xover_lines.append((elem[0], elem[1], elem[2], elem[3], elem[4], elem[5].split(), elem[6], elem[7]))
except IndexError:
... |
'Process an XGTITLE command (optional server extension) Arguments:
- group: group name wildcard (i.e. news.*)
Returns:
- resp: server response if successful
- list: list of (name,title) strings'
| def xgtitle(self, group, file=None):
| line_pat = re.compile('^([^ DCTB ]+)[ DCTB ]+(.*)$')
(resp, raw_lines) = self.longcmd(('XGTITLE ' + group), file)
lines = []
for raw_line in raw_lines:
match = line_pat.search(raw_line.strip())
if match:
lines.append(match.group(1, 2))
return (resp, lines)
|
'Process an XPATH command (optional server extension) Arguments:
- id: Message id of article
Returns:
resp: server response if successful
path: directory path to article'
| def xpath(self, id):
| resp = self.shortcmd(('XPATH ' + id))
if (resp[:3] != '223'):
raise NNTPReplyError(resp)
try:
[resp_num, path] = resp.split()
except ValueError:
raise NNTPReplyError(resp)
else:
return (resp, path)
|
'Process the DATE command. Arguments:
None
Returns:
resp: server response if successful
date: Date suitable for newnews/newgroups commands etc.
time: Time suitable for newnews/newgroups commands etc.'
| def date(self):
| resp = self.shortcmd('DATE')
if (resp[:3] != '111'):
raise NNTPReplyError(resp)
elem = resp.split()
if (len(elem) != 2):
raise NNTPDataError(resp)
date = elem[1][2:8]
time = elem[1][(-6):]
if ((len(date) != 6) or (len(time) != 6)):
raise NNTPDataError(resp)
return... |
'Process a POST command. Arguments:
- f: file containing the article
Returns:
- resp: server response if successful'
| def post(self, f):
| resp = self.shortcmd('POST')
if (resp[0] != '3'):
raise NNTPReplyError(resp)
while 1:
line = f.readline()
if (not line):
break
if (line[(-1)] == '\n'):
line = line[:(-1)]
if (line[:1] == '.'):
line = ('.' + line)
self.putlin... |
'Process an IHAVE command. Arguments:
- id: message-id of the article
- f: file containing the article
Returns:
- resp: server response if successful
Note that if the server refuses the article an exception is raised.'
| def ihave(self, id, f):
| resp = self.shortcmd(('IHAVE ' + id))
if (resp[0] != '3'):
raise NNTPReplyError(resp)
while 1:
line = f.readline()
if (not line):
break
if (line[(-1)] == '\n'):
line = line[:(-1)]
if (line[:1] == '.'):
line = ('.' + line)
... |
'Process a QUIT command and close the socket. Returns:
- resp: server response if successful'
| def quit(self):
| resp = self.shortcmd('QUIT')
self.file.close()
self.sock.close()
del self.file, self.sock
return resp
|
'Serve a GET request.'
| def do_GET(self):
| f = self.send_head()
if f:
try:
self.copyfile(f, self.wfile)
finally:
f.close()
|
'Serve a HEAD request.'
| def do_HEAD(self):
| f = self.send_head()
if f:
f.close()
|
'Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing furthe... | def send_head(self):
| path = self.translate_path(self.path)
f = None
if os.path.isdir(path):
parts = urlparse.urlsplit(self.path)
if (not parts.path.endswith('/')):
self.send_response(301)
new_parts = (parts[0], parts[1], (parts[2] + '/'), parts[3], parts[4])
new_url = urlparse... |
'Helper to produce a directory listing (absent index.html).
Return value is either a file object, or None (indicating an
error). In either case, the headers are sent, making the
interface the same as for send_head().'
| def list_directory(self, path):
| try:
list = os.listdir(path)
except os.error:
self.send_error(404, 'No permission to list directory')
return None
list.sort(key=(lambda a: a.lower()))
f = StringIO()
displaypath = cgi.escape(urllib.unquote(self.path))
f.write('<!DOCTYPE html PUBLIC "-... |
'Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)'
| def translate_path(self, path):
| path = path.split('?', 1)[0]
path = path.split('#', 1)[0]
trailing_slash = path.rstrip().endswith('/')
path = posixpath.normpath(urllib.unquote(path))
words = path.split('/')
words = filter(None, words)
path = os.getcwd()
for word in words:
if (os.path.dirname(word) or (word in (... |
'Copy all data between two file objects.
The SOURCE argument is a file object open for reading
(or anything with a read() method) and the DESTINATION
argument is a file object open for writing (or
anything with a write() method).
The only reason for overriding this would be to change
the block size or perhaps to replac... | def copyfile(self, source, outputfile):
| shutil.copyfileobj(source, outputfile)
|
'Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file\'s extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (... | def guess_type(self, path):
| (base, ext) = posixpath.splitext(path)
if (ext in self.extensions_map):
return self.extensions_map[ext]
ext = ext.lower()
if (ext in self.extensions_map):
return self.extensions_map[ext]
else:
return self.extensions_map['']
|
'Returns a dialect (or None) corresponding to the sample'
| def sniff(self, sample, delimiters=None):
| (quotechar, doublequote, delimiter, skipinitialspace) = self._guess_quote_and_delimiter(sample, delimiters)
if (not delimiter):
(delimiter, skipinitialspace) = self._guess_delimiter(sample, delimiters)
if (not delimiter):
raise Error, 'Could not determine delimiter'
class dialec... |
'Looks for text enclosed between two identical quotes
(the probable quotechar) which are preceded and followed
by the same character (the probable delimiter).
For example:
,\'some text\',
The quote with the most wins, same with the delimiter.
If there is no quotechar the delimiter can\'t be determined
this way.'
| def _guess_quote_and_delimiter(self, data, delimiters):
| matches = []
for restr in ('(?P<delim>[^\\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\\w\n"\'])(?P<space> ?)', '(?P<delim>>[^\\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n... |
'The delimiter /should/ occur the same number of times on
each row. However, due to malformed data, it may not. We don\'t want
an all or nothing approach, so we allow for small variations in this
number.
1) build a table of the frequency of each character on every line.
2) build a table of frequencies of this frequency... | def _guess_delimiter(self, data, delimiters):
| data = filter(None, data.split('\n'))
ascii = [chr(c) for c in range(127)]
chunkLength = min(10, len(data))
iteration = 0
charFrequency = {}
modes = {}
delims = {}
(start, end) = (0, min(chunkLength, len(data)))
while (start < len(data)):
iteration += 1
for line in da... |
'Registers an instance to respond to XML-RPC requests.
Only one instance can be installed at a time.
If the registered instance has a _dispatch method then that
method will be called with the name of the XML-RPC method and
its parameters as a tuple
e.g. instance._dispatch(\'add\',(2,3))
If the registered instance does ... | def register_instance(self, instance, allow_dotted_names=False):
| self.instance = instance
self.allow_dotted_names = allow_dotted_names
|
'Registers a function to respond to XML-RPC requests.
The optional name argument can be used to set a Unicode name
for the function.'
| def register_function(self, function, name=None):
| if (name is None):
name = function.__name__
self.funcs[name] = function
|
'Registers the XML-RPC introspection methods in the system
namespace.
see http://xmlrpc.usefulinc.com/doc/reserved.html'
| def register_introspection_functions(self):
| self.funcs.update({'system.listMethods': self.system_listMethods, 'system.methodSignature': self.system_methodSignature, 'system.methodHelp': self.system_methodHelp})
|
'Registers the XML-RPC multicall method in the system
namespace.
see http://www.xmlrpc.com/discuss/msgReader$1208'
| def register_multicall_functions(self):
| self.funcs.update({'system.multicall': self.system_multicall})
|
'Dispatches an XML-RPC method from marshalled (XML) data.
XML-RPC methods are dispatched from the marshalled (XML) data
using the _dispatch method and the result is returned as
marshalled data. For backwards compatibility, a dispatch
function can be provided as an argument (see comment in
SimpleXMLRPCRequestHandler.do_... | def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
| try:
(params, method) = xmlrpclib.loads(data)
if (dispatch_method is not None):
response = dispatch_method(method, params)
else:
response = self._dispatch(method, params)
response = (response,)
response = xmlrpclib.dumps(response, methodresponse=1, all... |
'system.listMethods() => [\'add\', \'subtract\', \'multiple\']
Returns a list of the methods supported by the server.'
| def system_listMethods(self):
| methods = self.funcs.keys()
if (self.instance is not None):
if hasattr(self.instance, '_listMethods'):
methods = remove_duplicates((methods + self.instance._listMethods()))
elif (not hasattr(self.instance, '_dispatch')):
methods = remove_duplicates((methods + list_public_... |
'system.methodSignature(\'add\') => [double, int, int]
Returns a list describing the signature of the method. In the
above example, the add method takes two integers as arguments
and returns a double result.
This server does NOT support system.methodSignature.'
| def system_methodSignature(self, method_name):
| return 'signatures not supported'
|
'system.methodHelp(\'add\') => "Adds two integers together"
Returns a string containing documentation for the specified method.'
| def system_methodHelp(self, method_name):
| method = None
if (method_name in self.funcs):
method = self.funcs[method_name]
elif (self.instance is not None):
if hasattr(self.instance, '_methodHelp'):
return self.instance._methodHelp(method_name)
elif (not hasattr(self.instance, '_dispatch')):
try:
... |
'system.multicall([{\'methodName\': \'add\', \'params\': [2, 2]}, ...]) => [[4], ...]
Allows the caller to package multiple XML-RPC calls into a single
request.
See http://www.xmlrpc.com/discuss/msgReader$1208'
| def system_multicall(self, call_list):
| results = []
for call in call_list:
method_name = call['methodName']
params = call['params']
try:
results.append([self._dispatch(method_name, params)])
except Fault as fault:
results.append({'faultCode': fault.faultCode, 'faultString': fault.faultString})
... |
'Dispatches the XML-RPC method.
XML-RPC calls are forwarded to a registered function that
matches the called XML-RPC method name. If no such function
exists then the call is forwarded to the registered instance,
if available.
If the registered instance has a _dispatch method then that
method will be called with the nam... | def _dispatch(self, method, params):
| func = None
try:
func = self.funcs[method]
except KeyError:
if (self.instance is not None):
if hasattr(self.instance, '_dispatch'):
return self.instance._dispatch(method, params)
else:
try:
func = resolve_dotted_attr... |
'Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server\'s _dispatch method for handling.'
| def do_POST(self):
| if (not self.is_rpc_path_valid()):
self.report_404()
return
try:
max_chunk_size = ((10 * 1024) * 1024)
size_remaining = int(self.headers['content-length'])
L = []
while size_remaining:
chunk_size = min(size_remaining, max_chunk_size)
chunk ... |
'Selectively log an accepted request.'
| def log_request(self, code='-', size='-'):
| if self.server.logRequests:
BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
|
'Handle a single XML-RPC request'
| def handle_xmlrpc(self, request_text):
| response = self._marshaled_dispatch(request_text)
print 'Content-Type: text/xml'
print ('Content-Length: %d' % len(response))
print
sys.stdout.write(response)
|
'Handle a single HTTP GET request.
Default implementation indicates an error because
XML-RPC uses the POST method.'
| def handle_get(self):
| code = 400
(message, explain) = BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
response = (BaseHTTPServer.DEFAULT_ERROR_MESSAGE % {'code': code, 'message': message, 'explain': explain})
print ('Status: %d %s' % (code, message))
print ('Content-Type: %s' % BaseHTTPServer.DEFAULT_ERROR... |
'Handle a single XML-RPC request passed through a CGI post method.
If no XML data is given then it is read from stdin. The resulting
XML-RPC response is printed to stdout along with the correct HTTP
headers.'
| def handle_request(self, request_text=None):
| if ((request_text is None) and (os.environ.get('REQUEST_METHOD', None) == 'GET')):
self.handle_get()
else:
try:
length = int(os.environ.get('CONTENT_LENGTH', None))
except (TypeError, ValueError):
length = (-1)
if (request_text is None):
reques... |
'Initialize a new instance, passing the time and delay
functions'
| def __init__(self, timefunc, delayfunc):
| self._queue = []
self.timefunc = timefunc
self.delayfunc = delayfunc
|
'Enter a new event in the queue at an absolute time.
Returns an ID for the event which can be used to remove it,
if necessary.'
| def enterabs(self, time, priority, action, argument):
| event = Event(time, priority, action, argument)
heapq.heappush(self._queue, event)
return event
|
'A variant that specifies the time as a relative time.
This is actually the more commonly used interface.'
| def enter(self, delay, priority, action, argument):
| time = (self.timefunc() + delay)
return self.enterabs(time, priority, action, argument)
|
'Remove an event from the queue.
This must be presented the ID as returned by enter().
If the event is not in the queue, this raises ValueError.'
| def cancel(self, event):
| self._queue.remove(event)
heapq.heapify(self._queue)
|
'Check whether the queue is empty.'
| def empty(self):
| return (not self._queue)
|
'Execute events until the queue is empty.
When there is a positive delay until the first event, the
delay function is called and the event is left in the queue;
otherwise, the event is removed from the queue and executed
(its action function is called, passing it the argument). If
the delay function returns prematurel... | def run(self):
| q = self._queue
delayfunc = self.delayfunc
timefunc = self.timefunc
pop = heapq.heappop
while q:
(time, priority, action, argument) = checked_event = q[0]
now = timefunc()
if (now < time):
delayfunc((time - now))
else:
event = pop(q)
... |
'An ordered list of upcoming events.
Events are named tuples with fields for:
time, priority, action, arguments'
| @property
def queue(self):
| events = self._queue[:]
return map(heapq.heappop, ([events] * len(events)))
|
'Return the name (ID) of the current chunk.'
| def getname(self):
| return self.chunkname
|
'Return the size of the current chunk.'
| def getsize(self):
| return self.chunksize
|
'Seek to specified position into the chunk.
Default position is 0 (start of chunk).
If the file is not seekable, this will result in an error.'
| def seek(self, pos, whence=0):
| if self.closed:
raise ValueError, 'I/O operation on closed file'
if (not self.seekable):
raise IOError, 'cannot seek'
if (whence == 1):
pos = (pos + self.size_read)
elif (whence == 2):
pos = (pos + self.chunksize)
if ((pos < 0) or (pos > self.chunksize)... |
'Read at most size bytes from the chunk.
If size is omitted or negative, read until the end
of the chunk.'
| def read(self, size=(-1)):
| if self.closed:
raise ValueError, 'I/O operation on closed file'
if (self.size_read >= self.chunksize):
return ''
if (size < 0):
size = (self.chunksize - self.size_read)
if (size > (self.chunksize - self.size_read)):
size = (self.chunksize - self.size_read)
... |
'Skip the rest of the chunk.
If you are not interested in the contents of the chunk,
this method should be called so that the file points to
the start of the next chunk.'
| def skip(self):
| if self.closed:
raise ValueError, 'I/O operation on closed file'
if self.seekable:
try:
n = (self.chunksize - self.size_read)
if (self.align and (self.chunksize & 1)):
n = (n + 1)
self.file.seek(n, 1)
self.size_read = (s... |
'Go to the location of the first blank on the given line,
returning the index of the last non-blank character.'
| def _end_of_line(self, y):
| last = self.maxx
while True:
if (curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP):
last = min(self.maxx, (last + 1))
break
elif (last == 0):
break
last = (last - 1)
return last
|
'Process a single editing command.'
| def do_command(self, ch):
| (y, x) = self.win.getyx()
self.lastcmd = ch
if curses.ascii.isprint(ch):
if ((y < self.maxy) or (x < self.maxx)):
self._insert_printable_char(ch)
elif (ch == curses.ascii.SOH):
self.win.move(y, 0)
elif (ch in (curses.ascii.STX, curses.KEY_LEFT, curses.ascii.BS, curses.KEY... |
'Collect and return the contents of the window.'
| def gather(self):
| result = ''
for y in range((self.maxy + 1)):
self.win.move(y, 0)
stop = self._end_of_line(y)
if ((stop == 0) and self.stripspaces):
continue
for x in range((self.maxx + 1)):
if (self.stripspaces and (x > stop)):
break
result = (... |
'Edit in the widget window and collect the results.'
| def edit(self, validate=None):
| while 1:
ch = self.win.getch()
if validate:
ch = validate(ch)
if (not ch):
continue
if (not self.do_command(ch)):
break
self.win.refresh()
return self.gather()
|
'Constructor.'
| def __init__(self, path=None, profile=None):
| if (profile is None):
profile = MH_PROFILE
self.profile = os.path.expanduser(profile)
if (path is None):
path = self.getprofile('Path')
if (not path):
path = PATH
if ((not os.path.isabs(path)) and (path[0] != '~')):
path = os.path.join('~', path)
path = os.path.ex... |
'String representation.'
| def __repr__(self):
| return ('MH(%r, %r)' % (self.path, self.profile))
|
'Routine to print an error. May be overridden by a derived class.'
| def error(self, msg, *args):
| sys.stderr.write(('MH error: %s\n' % (msg % args)))
|
'Return a profile entry, None if not found.'
| def getprofile(self, key):
| return pickline(self.profile, key)
|
'Return the path (the name of the collection\'s directory).'
| def getpath(self):
| return self.path
|
'Return the name of the current folder.'
| def getcontext(self):
| context = pickline(os.path.join(self.getpath(), 'context'), 'Current-Folder')
if (not context):
context = 'inbox'
return context
|
'Set the name of the current folder.'
| def setcontext(self, context):
| fn = os.path.join(self.getpath(), 'context')
f = open(fn, 'w')
f.write(('Current-Folder: %s\n' % context))
f.close()
|
'Return the names of the top-level folders.'
| def listfolders(self):
| folders = []
path = self.getpath()
for name in os.listdir(path):
fullname = os.path.join(path, name)
if os.path.isdir(fullname):
folders.append(name)
folders.sort()
return folders
|
'Return the names of the subfolders in a given folder
(prefixed with the given folder name).'
| def listsubfolders(self, name):
| fullname = os.path.join(self.path, name)
nlinks = os.stat(fullname).st_nlink
if (nlinks <= 2):
return []
subfolders = []
subnames = os.listdir(fullname)
for subname in subnames:
fullsubname = os.path.join(fullname, subname)
if os.path.isdir(fullsubname):
name_... |
'Return the names of all folders and subfolders, recursively.'
| def listallfolders(self):
| return self.listallsubfolders('')
|
'Return the names of subfolders in a given folder, recursively.'
| def listallsubfolders(self, name):
| fullname = os.path.join(self.path, name)
nlinks = os.stat(fullname).st_nlink
if (nlinks <= 2):
return []
subfolders = []
subnames = os.listdir(fullname)
for subname in subnames:
if ((subname[0] == ',') or isnumeric(subname)):
continue
fullsubname = os.path.joi... |
'Return a new Folder object for the named folder.'
| def openfolder(self, name):
| return Folder(self, name)
|
'Create a new folder (or raise os.error if it cannot be created).'
| def makefolder(self, name):
| protect = pickline(self.profile, 'Folder-Protect')
if (protect and isnumeric(protect)):
mode = int(protect, 8)
else:
mode = FOLDER_PROTECT
os.mkdir(os.path.join(self.getpath(), name), mode)
|
'Delete a folder. This removes files in the folder but not
subdirectories. Raise os.error if deleting the folder itself fails.'
| def deletefolder(self, name):
| fullname = os.path.join(self.getpath(), name)
for subname in os.listdir(fullname):
fullsubname = os.path.join(fullname, subname)
try:
os.unlink(fullsubname)
except os.error:
self.error(('%s not deleted, continuing...' % fullsubname))
os.rmdir(fullname... |
'Constructor.'
| def __init__(self, mh, name):
| self.mh = mh
self.name = name
if (not os.path.isdir(self.getfullname())):
raise Error, ('no folder %s' % name)
|
'String representation.'
| def __repr__(self):
| return ('Folder(%r, %r)' % (self.mh, self.name))
|
'Error message handler.'
| def error(self, *args):
| self.mh.error(*args)
|
'Return the full pathname of the folder.'
| def getfullname(self):
| return os.path.join(self.mh.path, self.name)
|
'Return the full pathname of the folder\'s sequences file.'
| def getsequencesfilename(self):
| return os.path.join(self.getfullname(), MH_SEQUENCES)
|
'Return the full pathname of a message in the folder.'
| def getmessagefilename(self, n):
| return os.path.join(self.getfullname(), str(n))
|
'Return list of direct subfolders.'
| def listsubfolders(self):
| return self.mh.listsubfolders(self.name)
|
'Return list of all subfolders.'
| def listallsubfolders(self):
| return self.mh.listallsubfolders(self.name)
|
'Return the list of messages currently present in the folder.
As a side effect, set self.last to the last message (or 0).'
| def listmessages(self):
| messages = []
match = numericprog.match
append = messages.append
for name in os.listdir(self.getfullname()):
if match(name):
append(name)
messages = map(int, messages)
messages.sort()
if messages:
self.last = messages[(-1)]
else:
self.last = 0
retu... |
'Return the set of sequences for the folder.'
| def getsequences(self):
| sequences = {}
fullname = self.getsequencesfilename()
try:
f = open(fullname, 'r')
except IOError:
return sequences
while 1:
line = f.readline()
if (not line):
break
fields = line.split(':')
if (len(fields) != 2):
self.error(('b... |
'Write the set of sequences back to the folder.'
| def putsequences(self, sequences):
| fullname = self.getsequencesfilename()
f = None
for (key, seq) in sequences.iteritems():
s = IntSet('', ' ')
s.fromlist(seq)
if (not f):
f = open(fullname, 'w')
f.write(('%s: %s\n' % (key, s.tostring())))
if (not f):
try:
os.unlink(fu... |
'Return the current message. Raise Error when there is none.'
| def getcurrent(self):
| seqs = self.getsequences()
try:
return max(seqs['cur'])
except (ValueError, KeyError):
raise Error, 'no cur message'
|
'Set the current message.'
| def setcurrent(self, n):
| updateline(self.getsequencesfilename(), 'cur', str(n), 0)
|
'Parse an MH sequence specification into a message list.
Attempt to mimic mh-sequence(5) as close as possible.
Also attempt to mimic observed behavior regarding which
conditions cause which error messages.'
| def parsesequence(self, seq):
| all = self.listmessages()
if (not all):
raise Error, ('no messages in %s' % self.name)
if (seq == 'all'):
return all
i = seq.find(':')
if (i >= 0):
(head, dir, tail) = (seq[:i], '', seq[(i + 1):])
if (tail[:1] in '-+'):
(dir, tail) = (tail[:1], ta... |
'Internal: parse a message number (or cur, first, etc.).'
| def _parseindex(self, seq, all):
| if isnumeric(seq):
try:
return int(seq)
except (OverflowError, ValueError):
return sys.maxint
if (seq in ('cur', '.')):
return self.getcurrent()
if (seq == 'first'):
return all[0]
if (seq == 'last'):
return all[(-1)]
if (seq == 'next'):... |
'Open a message -- returns a Message object.'
| def openmessage(self, n):
| return Message(self, n)
|
'Remove one or more messages -- may raise os.error.'
| def removemessages(self, list):
| errors = []
deleted = []
for n in list:
path = self.getmessagefilename(n)
commapath = self.getmessagefilename((',' + str(n)))
try:
os.unlink(commapath)
except os.error:
pass
try:
os.rename(path, commapath)
except os.error as... |
'Refile one or more messages -- may raise os.error.
\'tofolder\' is an open folder object.'
| def refilemessages(self, list, tofolder, keepsequences=0):
| errors = []
refiled = {}
for n in list:
ton = (tofolder.getlast() + 1)
path = self.getmessagefilename(n)
topath = tofolder.getmessagefilename(ton)
try:
os.rename(path, topath)
except os.error:
try:
shutil.copy2(path, topath)
... |
'Helper for refilemessages() to copy sequences.'
| def _copysequences(self, fromfolder, refileditems):
| fromsequences = fromfolder.getsequences()
tosequences = self.getsequences()
changed = 0
for (name, seq) in fromsequences.items():
try:
toseq = tosequences[name]
new = 0
except KeyError:
toseq = []
new = 1
for (fromn, ton) in refiled... |
'Move one message over a specific destination message,
which may or may not already exist.'
| def movemessage(self, n, tofolder, ton):
| path = self.getmessagefilename(n)
f = open(path)
f.close()
del f
topath = tofolder.getmessagefilename(ton)
backuptopath = tofolder.getmessagefilename((',%d' % ton))
try:
os.rename(topath, backuptopath)
except os.error:
pass
try:
os.rename(path, topath)
exc... |
'Copy one message over a specific destination message,
which may or may not already exist.'
| def copymessage(self, n, tofolder, ton):
| path = self.getmessagefilename(n)
f = open(path)
f.close()
del f
topath = tofolder.getmessagefilename(ton)
backuptopath = tofolder.getmessagefilename((',%d' % ton))
try:
os.rename(topath, backuptopath)
except os.error:
pass
ok = 0
try:
tofolder.setlast(Non... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.