]> khamidou — GitHub mirrors - imapclient.git/commitdiff
Added literal support
authorMenno Smits <menno@freshfoo.com>
Sat, 14 Nov 2009 17:21:19 +0000 (17:21 +0000)
committerMenno Smits <menno@freshfoo.com>
Sat, 14 Nov 2009 17:21:19 +0000 (17:21 +0000)
Refactored tokenising code to allow directory access to the stream.

imapclient/imapclient.py
imapclient/response_parser.py
imapclient/test/test_response_parser.py
run_altfetch.py

index 924591b0899cf0935b1d2102979ac967115bf1c3..7454c669a725cd55310ee5b0234a564940fbad61 100644 (file)
@@ -449,7 +449,6 @@ class IMAPClient(object):
 
 
     def altfetch(self, messages, parts):
-        import pdb; pdb.set_trace()
         if not messages:
             return {}
 
index 5545bf0c86d282af9ca86b1d753c6f008e18ffdc..cdaf6d1d5c8eceff1115921717017ef7e6fe3a27 100644 (file)
@@ -2,40 +2,53 @@
 
 import shlex
 
-CTRL_CHARS = ''.join([chr(ch) for ch in range(32)])
-ATOM_SPECIALS = r'(){%*\"]' + CTRL_CHARS
-ALL_CHARS = [chr(ch) for ch in range(256)]
-ATOM_NON_SPECIALS = [ch for ch in ALL_CHARS if ch not in ATOM_SPECIALS]
-
-#XXX literals
 #XXX error handling: needs to be friendly
 #XXX higher level response type response type processing
 
 __all__ = ['parse_response', 'ParseError']
 
+
 class ParseError(ValueError):
     pass
 
 
-def generate_tokens(text):
-    lex = shlex.shlex(text)
-    lex.quotes = '"'
-    lex.commenters = ''
-    lex.wordchars = ATOM_NON_SPECIALS
-    for token in lex:
-        yield token
+class ResponseTokeniser(object):
+
+    CTRL_CHARS = ''.join([chr(ch) for ch in range(32)])
+    ATOM_SPECIALS = r'()%*\"]' + CTRL_CHARS
+    ALL_CHARS = [chr(ch) for ch in range(256)]
+    ATOM_NON_SPECIALS = [ch for ch in ALL_CHARS if ch not in ATOM_SPECIALS]
+
+    def __init__(self, text):
+        self.lex = shlex.shlex(text)
+        self.lex.quotes = '"'
+        self.lex.commenters = ''
+        self.lex.wordchars = self.ATOM_NON_SPECIALS
+
+    def __iter__(self):
+        return iter(self.lex)
+
+    def next(self):
+        return self.lex.next()
+
+    def read(self, bytes):
+        return self.lex.instream.read(bytes)
 
 
-def atom(next, token):
+def atom(src, token):
     if token == "(":
         out = []
-        token = next()
+        token = src.next()
         while token != ")":
-            out.append(atom(next, token))
-            token = next()
+            out.append(atom(src, token))
+            token = src.next()
         return tuple(out)
     elif token == 'NIL':
         return None
+    elif token.startswith('{'):
+        literal_len = int(token[1:-1])
+        assert src.read(1) == '\n' #XXX use ParseError
+        return src.read(literal_len)
     elif token.startswith('"'):
         return token[1:-1]
     elif token.isdigit():
@@ -45,6 +58,6 @@ def atom(next, token):
 
 
 def parse_response(text):
-    src = generate_tokens(text)
-    return tuple([atom(src.next, token) for token in src])
+    src = ResponseTokeniser(text)
+    return tuple([atom(src, token) for token in src])
 
index e7be7deccb0255f6ae0de05ae0cf8257d6eb169d..0c08f8df173769f75de73c286dcc02cff2fe749c 100644 (file)
@@ -18,6 +18,7 @@
 Unit tests for the FetchTokeniser and FetchParser classes
 '''
 
+from textwrap import dedent
 import unittest
 from imapclient.response_parser import parse_response
 from imapclient.fixed_offset import FixedOffset
@@ -32,6 +33,7 @@ system_offset = FixedOffset.for_system()
 def datetime_to_native(dt):
     return dt.astimezone(system_offset).replace(tzinfo=None)
 
+CRLF = '\r\n'
 
 class TestParseResponse(unittest.TestCase):
 
@@ -69,6 +71,27 @@ class TestParseResponse(unittest.TestCase):
                     ('TEXT', 'PLAIN', ('CHARSET', 'US-ASCII', 'NAME', 'cc.diff'),
                     '<hi.there>', 'foo', 'BASE64', 4554, 73), 'MIXED'))
 
+
+    def test_literal(self):
+        literal_text = add_crlf(dedent("""\
+            012
+            abc def XYZ
+            """))
+        self._test('{18}' + CRLF + literal_text, literal_text)
+
+
+    def test_literal_with_more(self):
+        literal_text = add_crlf(dedent("""\
+            012
+            abc def XYZ
+            """))
+        response = add_crlf(dedent("""\
+            (12 "foo" {18}
+            %s)
+            """) % literal_text)
+        self._test(response, (12, 'foo', literal_text))
+
+
     def _test(self, to_parse, expected, wrap=True):
         # convenience - expected value should be wrapped in another tuple
         if wrap:
@@ -78,6 +101,10 @@ class TestParseResponse(unittest.TestCase):
                 output == expected,
                 format_error(to_parse, output, expected),
             )
+
+
+#TODO convert the following are mainly FETCH specific tests
+
 #     def testCharacterCase(self):
 #         '''Test handling of varied case in the response type name
 #         '''
@@ -213,6 +240,11 @@ def format_error(input_, output, expected):
                 pformat(expected),
             )
 
+
+def add_crlf(text):
+    return CRLF.join(text.splitlines()) + CRLF
+
+
 # class TestFetchTokeniser(unittest.TestCase):
 #     def setUp(self):
 #         self.t = FetchTokeniser()
@@ -286,10 +318,5 @@ def format_error(input_, output, expected):
 # example3 = '1 FETCH (UID 1 INTERNALDATE "18-Oct-2009 19:59:06 +0100")'
 # err1 = '1 FETCH (UID '
 
-# print parse_response(example1)
-# print parse_response(example2)
-# print parse_response(example3)
-# print parse_response(err1)
-
 if __name__ == '__main__':
     unittest.main()
index e1dc4dd01fbd6c02f5950868c535a2829d397403..0cf8ea75de7a8dbebf8bae653e4b6b4229d9d998 100644 (file)
@@ -6,9 +6,15 @@ def main():
     i.login('mailtest', 'foobar')
     i.select_folder('INBOX')
     msgs = i.search()
-    print msgs
     i._imap.debug = 5
-    pprint(i.altfetch(msgs[0], 'RFC822'))
+    lines = i.altfetch(msgs[0], ['RFC822'])
+
+    print lines[0]
+    body = '\r\n'.join(lines[1:-1])
+    body += '\r\n'
+    print body
+    print len(body)
+
 
 if __name__ == '__main__':
     main()