[PATCH 01/15] Raise exceptions as defined in PEP 3109
Łukasz Żarnowiecki
dolohow at outlook.com
Tue May 17 18:56:52 BST 2016
>From 3939bfb172ceb0c212a2d055abf64bdbc218dee7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C5=81ukasz=20=C5=BBarnowiecki?= <dolohow at outlook.com>
Date: Tue, 17 May 2016 19:49:52 +0200
Subject: [PATCH] Raise exceptions using six module
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
There is no other way to make Python2 and Python3 happy, because syntax
raise E, V, T is incompatible with the latter.
Signed-off-by: Łukasz Żarnowiecki <dolohow at outlook.com>
---
offlineimap/CustomConfig.py | 6 ++++--
offlineimap/accounts.py | 10 ++++++----
offlineimap/folder/Gmail.py | 7 ++++---
offlineimap/folder/GmailMaildir.py | 7 ++++---
offlineimap/folder/IMAP.py | 15 ++++++++-------
offlineimap/folder/LocalStatus.py | 6 ++++--
offlineimap/folder/LocalStatusSQLite.py | 11 +++++++----
offlineimap/folder/Maildir.py | 16 +++++++++-------
offlineimap/folder/UIDMaps.py | 10 ++++++----
offlineimap/imaplibutil.py | 4 +++-
offlineimap/imapserver.py | 12 +++++++-----
offlineimap/repository/IMAP.py | 7 ++++---
offlineimap/repository/__init__.py | 8 ++++----
13 files changed, 70 insertions(+), 49 deletions(-)
diff --git a/offlineimap/CustomConfig.py b/offlineimap/CustomConfig.py
index 44cfcab..bb9eaa7 100644
--- a/offlineimap/CustomConfig.py
+++ b/offlineimap/CustomConfig.py
@@ -18,6 +18,8 @@ import os
import re
from sys import exc_info
+import six
+
try:
from ConfigParser import SafeConfigParser, Error
except ImportError: #python3
@@ -75,8 +77,8 @@ class CustomConfigParser(SafeConfigParser):
val = self.get(section, option).strip()
return re.split(separator_re, val)
except re.error as e:
- raise Error("Bad split regexp '%s': %s" % \
- (separator_re, e)), None, exc_info()[2]
+ six.reraise(Error("Bad split regexp '%s': %s" % \
+ (separator_re, e)), None, exc_info()[2])
def getdefaultlist(self, section, option, default, separator_re):
"""Same as getlist, but returns the value of `default`
diff --git a/offlineimap/accounts.py b/offlineimap/accounts.py
index 5acd82a..9975fda 100644
--- a/offlineimap/accounts.py
+++ b/offlineimap/accounts.py
@@ -27,6 +27,8 @@ from offlineimap.repository import Repository
from offlineimap.ui import getglobalui
from offlineimap.threadutil import InstanceLimitedThread
+import six
+
try:
import fcntl
except:
@@ -226,9 +228,9 @@ class SyncableAccount(Account):
pass
except IOError:
self._lockfd.close()
- raise OfflineImapError("Could not lock account %s. Is another "
+ six.reraise(OfflineImapError("Could not lock account %s. Is another "
"instance using this account?"% self,
- OfflineImapError.ERROR.REPO), None, exc_info()[2]
+ OfflineImapError.ERROR.REPO), None, exc_info()[2])
def _unlock(self):
"""Unlock the account, deleting the lock file"""
@@ -534,10 +536,10 @@ def syncfolder(account, remotefolder, quick):
localstart = localfolder.getstartdate()
remotestart = remotefolder.getstartdate()
if (maxage != None) + (localstart != None) + (remotestart != None) > 1:
- raise OfflineImapError("You can set at most one of the "
+ six.reraise(OfflineImapError("You can set at most one of the "
"following: maxage, startdate (for the local folder), "
"startdate (for the remote folder)",
- OfflineImapError.ERROR.REPO), None, exc_info()[2]
+ OfflineImapError.ERROR.REPO), None, exc_info()[2])
if (maxage != None or localstart or remotestart) and quick:
# IMAP quickchanged isn't compatible with options that
# involve restricting the messagelist, since the "quick"
diff --git a/offlineimap/folder/Gmail.py b/offlineimap/folder/Gmail.py
index 0abd221..968e23e 100644
--- a/offlineimap/folder/Gmail.py
+++ b/offlineimap/folder/Gmail.py
@@ -24,6 +24,8 @@ from offlineimap import imaplibutil
import offlineimap.accounts
from .IMAP import IMAPFolder
+import six
+
"""Folder implementation to support features of the Gmail IMAP server."""
class GmailFolder(IMAPFolder):
@@ -139,11 +141,10 @@ class GmailFolder(IMAPFolder):
res_type, response = imapobj.fetch("'%s'"% msgsToFetch,
'(FLAGS X-GM-LABELS UID)')
if res_type != 'OK':
- raise OfflineImapError("FETCHING UIDs in folder [%s]%s failed. " % \
+ six.reraise(OfflineImapError("FETCHING UIDs in folder [%s]%s failed. " % \
(self.getrepository(), self) + \
"Server responded '[%s] %s'" % \
- (res_type, response), OfflineImapError.ERROR.FOLDER), \
- None, exc_info()[2]
+ (res_type, response), OfflineImapError.ERROR.FOLDER), None, exc_info()[2])
finally:
self.imapserver.releaseconnection(imapobj)
diff --git a/offlineimap/folder/GmailMaildir.py b/offlineimap/folder/GmailMaildir.py
index c27c027..71624a2 100644
--- a/offlineimap/folder/GmailMaildir.py
+++ b/offlineimap/folder/GmailMaildir.py
@@ -23,6 +23,8 @@ from offlineimap import OfflineImapError
import offlineimap.accounts
from offlineimap import imaputil
+import six
+
class GmailMaildirFolder(MaildirFolder):
"""Folder implementation to support adding labels to messages in a Maildir.
"""
@@ -170,9 +172,8 @@ class GmailMaildirFolder(MaildirFolder):
try:
os.rename(tmppath, filepath)
except OSError as e:
- raise OfflineImapError("Can't rename file '%s' to '%s': %s" % \
- (tmppath, filepath, e[1]), OfflineImapError.ERROR.FOLDER), \
- None, exc_info()[2]
+ six.reraise(OfflineImapError("Can't rename file '%s' to '%s': %s" % \
+ (tmppath, filepath, e[1]), OfflineImapError.ERROR.FOLDER), None, exc_info()[2])
# if utime_from_header=true, we don't want to change the mtime.
if self.utime_from_header and mtime:
diff --git a/offlineimap/folder/IMAP.py b/offlineimap/folder/IMAP.py
index e88a696..aa59954 100644
--- a/offlineimap/folder/IMAP.py
+++ b/offlineimap/folder/IMAP.py
@@ -27,6 +27,8 @@ from offlineimap import imaputil, imaplibutil, emailutil, OfflineImapError
from offlineimap import globals
from offlineimap.imaplib2 import MonthNames
+import six
+
# Globals
CRLF = '\r\n'
@@ -82,8 +84,8 @@ class IMAPFolder(BaseFolder):
def getmaxage(self):
if self.config.getdefault("Account %s"%
self.accountname, "maxage", None):
- raise OfflineImapError("maxage is not supported on IMAP-IMAP sync",
- OfflineImapError.ERROR.REPO), None, exc_info()[2]
+ six.reraise(OfflineImapError("maxage is not supported on IMAP-IMAP sync",
+ OfflineImapError.ERROR.REPO), None, exc_info()[2])
# Interface from BaseFolder
def getcopyinstancelimit(self):
@@ -607,12 +609,11 @@ class IMAPFolder(BaseFolder):
self.imapserver.releaseconnection(imapobj, True)
imapobj = self.imapserver.acquireconnection()
if not retry_left:
- raise OfflineImapError("Saving msg (%s) in folder '%s', "
+ six.reraise(OfflineImapError("Saving msg (%s) in folder '%s', "
"repository '%s' failed (abort). Server responded: %s\n"
"Message content was: %s"%
(msg_id, self, self.getrepository(), str(e), dbg_output),
- OfflineImapError.ERROR.MESSAGE), \
- None, exc_info()[2]
+ OfflineImapError.ERROR.MESSAGE), None, exc_info()[2])
# XXX: is this still needed?
self.ui.error(e, exc_info()[2])
except imapobj.error as e: # APPEND failed
@@ -621,10 +622,10 @@ class IMAPFolder(BaseFolder):
# drop conn, it might be bad.
self.imapserver.releaseconnection(imapobj, True)
imapobj = None
- raise OfflineImapError("Saving msg (%s) folder '%s', repo '%s'"
+ six.reraise(OfflineImapError("Saving msg (%s) folder '%s', repo '%s'"
"failed (error). Server responded: %s\nMessage content was: "
"%s" % (msg_id, self, self.getrepository(), str(e), dbg_output),
- OfflineImapError.ERROR.MESSAGE), None, exc_info()[2]
+ OfflineImapError.ERROR.MESSAGE), None, exc_info()[2])
# Checkpoint. Let it write out stuff, etc. Eg searches for
# just uploaded messages won't work if we don't do this.
(typ,dat) = imapobj.check()
diff --git a/offlineimap/folder/LocalStatus.py b/offlineimap/folder/LocalStatus.py
index e5d4ccf..31b04dd 100644
--- a/offlineimap/folder/LocalStatus.py
+++ b/offlineimap/folder/LocalStatus.py
@@ -21,6 +21,8 @@ import threading
from .Base import BaseFolder
+import six
+
class LocalStatusFolder(BaseFolder):
"""LocalStatus backend implemented as a plain text file."""
@@ -74,7 +76,7 @@ class LocalStatusFolder(BaseFolder):
errstr = "Corrupt line '%s' in cache file '%s'" % \
(line, self.filename)
self.ui.warn(errstr)
- raise ValueError(errstr), None, exc_info()[2]
+ six.reraise(ValueError(errstr), None, exc_info()[2])
self.messagelist[uid] = self.msglist_item_initializer(uid)
self.messagelist[uid]['flags'] = flags
@@ -97,7 +99,7 @@ class LocalStatusFolder(BaseFolder):
errstr = "Corrupt line '%s' in cache file '%s'"% \
(line, self.filename)
self.ui.warn(errstr)
- raise ValueError(errstr), None, exc_info()[2]
+ six.reraise(ValueError(errstr), None, exc_info()[2])
self.messagelist[uid] = self.msglist_item_initializer(uid)
self.messagelist[uid]['flags'] = flags
self.messagelist[uid]['mtime'] = mtime
diff --git a/offlineimap/folder/LocalStatusSQLite.py b/offlineimap/folder/LocalStatusSQLite.py
index 1a9f03c..b5e0f50 100644
--- a/offlineimap/folder/LocalStatusSQLite.py
+++ b/offlineimap/folder/LocalStatusSQLite.py
@@ -17,6 +17,9 @@
import os
from sys import exc_info
from threading import Lock
+
+import six
+
try:
import sqlite3 as sqlite
except:
@@ -68,15 +71,15 @@ class LocalStatusSQLiteFolder(BaseFolder):
self.connection = sqlite.connect(self.filename, check_same_thread=False)
except NameError:
# sqlite import had failed.
- raise UserWarning("SQLite backend chosen, but cannot connect "
+ six.reraise(UserWarning("SQLite backend chosen, but cannot connect "
"with available bindings to '%s'. Is the sqlite3 package "
- "installed?."% self.filename), None, exc_info()[2]
+ "installed?."% self.filename), None, exc_info()[2])
except sqlite.OperationalError as e:
# Operation had failed.
- raise UserWarning("cannot open database file '%s': %s.\nYou might "
+ six.reraise(UserWarning("cannot open database file '%s': %s.\nYou might "
"want to check the rights to that file and if it cleanly opens "
"with the 'sqlite<3>' command."%
- (self.filename, e)), None, exc_info()[2]
+ (self.filename, e)), None, exc_info()[2])
# Make sure sqlite is in multithreading SERIALIZE mode.
assert sqlite.threadsafety == 1, 'Your sqlite is not multithreading safe.'
diff --git a/offlineimap/folder/Maildir.py b/offlineimap/folder/Maildir.py
index 58e4cad..646b4f6 100644
--- a/offlineimap/folder/Maildir.py
+++ b/offlineimap/folder/Maildir.py
@@ -22,6 +22,9 @@ import os
from sys import exc_info
from .Base import BaseFolder
from threading import Lock
+
+import six
+
try:
from hashlib import md5
except ImportError:
@@ -309,8 +312,8 @@ class MaildirFolder(BaseFolder):
time.sleep(0.23)
continue
severity = OfflineImapError.ERROR.MESSAGE
- raise OfflineImapError("Unique filename %s already exists."%
- filename, severity), None, exc_info()[2]
+ six.reraise(OfflineImapError("Unique filename %s already exists."%
+ filename, severity), None, exc_info()[2])
else:
raise
@@ -430,10 +433,9 @@ class MaildirFolder(BaseFolder):
os.rename(os.path.join(self.getfullname(), oldfilename),
os.path.join(self.getfullname(), newfilename))
except OSError as e:
- raise OfflineImapError("Can't rename file '%s' to '%s': %s" % (
+ six.reraise(OfflineImapError("Can't rename file '%s' to '%s': %s" % (
oldfilename, newfilename, e[1]),
- OfflineImapError.ERROR.FOLDER), \
- None, exc_info()[2]
+ OfflineImapError.ERROR.FOLDER), None, exc_info()[2])
self.messagelist[uid]['flags'] = flags
self.messagelist[uid]['filename'] = newfilename
@@ -511,10 +513,10 @@ class MaildirFolder(BaseFolder):
try:
os.rename(filename, newfilename)
except OSError as e:
- raise OfflineImapError(
+ six.reraise(OfflineImapError(
"Can't rename file '%s' to '%s': %s" % (
filename, newfilename, e[1]),
- OfflineImapError.ERROR.FOLDER), None, exc_info()[2]
+ OfflineImapError.ERROR.FOLDER), None, exc_info()[2])
elif match.group(1) != self._foldermd5:
self.ui.warn(("Inconsistent FMD5 for file `%s':"
" Neither `%s' nor `%s' found")
diff --git a/offlineimap/folder/UIDMaps.py b/offlineimap/folder/UIDMaps.py
index 67f220c..45c94bd 100644
--- a/offlineimap/folder/UIDMaps.py
+++ b/offlineimap/folder/UIDMaps.py
@@ -21,6 +21,8 @@ from offlineimap import OfflineImapError
from .IMAP import IMAPFolder
import os.path
+import six
+
class MappedIMAPFolder(IMAPFolder):
"""IMAP class to map between Folder() instances where both side assign a uid
@@ -61,8 +63,8 @@ class MappedIMAPFolder(IMAPFolder):
try:
line = line.strip()
except ValueError:
- raise Exception("Corrupt line '%s' in UID mapping file '%s'"%
- (line, mapfilename)), None, exc_info()[2]
+ six.reraise(Exception("Corrupt line '%s' in UID mapping file '%s'"%
+ (line, mapfilename)), None, exc_info()[2])
(str1, str2) = line.split(':')
loc = int(str1)
rem = int(str2)
@@ -88,10 +90,10 @@ class MappedIMAPFolder(IMAPFolder):
try:
return [mapping[x] for x in items]
except KeyError as e:
- raise OfflineImapError("Could not find UID for msg '{0}' (f:'{1}'."
+ six.reraise(OfflineImapError("Could not find UID for msg '{0}' (f:'{1}'."
" This is usually a bad thing and should be reported on the ma"
"iling list.".format(e.args[0], self),
- OfflineImapError.ERROR.MESSAGE), None, exc_info()[2]
+ OfflineImapError.ERROR.MESSAGE), None, exc_info()[2])
# Interface from BaseFolder
def cachemessagelist(self, min_date=None, min_uid=None):
diff --git a/offlineimap/imaplibutil.py b/offlineimap/imaplibutil.py
index fc48000..32448b7 100644
--- a/offlineimap/imaplibutil.py
+++ b/offlineimap/imaplibutil.py
@@ -28,6 +28,8 @@ from offlineimap.ui import getglobalui
from offlineimap import OfflineImapError
from offlineimap.imaplib2 import IMAP4, IMAP4_SSL, zlib, InternalDate, Mon2num
+import six
+
class UsefulIMAPMixIn(object):
def __getselectedfolder(self):
@@ -56,7 +58,7 @@ class UsefulIMAPMixIn(object):
errstr = "Server '%s' closed connection, error on SELECT '%s'. Ser"\
"ver said: %s" % (self.host, mailbox, e.args[0])
severity = OfflineImapError.ERROR.FOLDER_RETRY
- raise OfflineImapError(errstr, severity), None, exc_info()[2]
+ six.reraise(OfflineImapError(errstr, severity), None, exc_info()[2])
if result[0] != 'OK':
#in case of error, bail out with OfflineImapError
errstr = "Error SELECTing mailbox '%s', server reply:\n%s" %\
diff --git a/offlineimap/imapserver.py b/offlineimap/imapserver.py
index 9d30544..14aa753 100644
--- a/offlineimap/imapserver.py
+++ b/offlineimap/imapserver.py
@@ -34,6 +34,8 @@ from offlineimap import imaplibutil, imaputil, threadutil, OfflineImapError
import offlineimap.accounts
from offlineimap.ui import getglobalui
+import six
+
try:
# do we have a recent pykerberos?
@@ -570,7 +572,7 @@ class IMAPServer:
"'%s'. Make sure you have configured the ser"\
"ver name correctly and that you are online."%\
(self.hostname, self.repos)
- raise OfflineImapError(reason, severity), None, exc_info()[2]
+ six.reraise(OfflineImapError(reason, severity), None, exc_info()[2])
elif isinstance(e, SSLError) and e.errno == errno.EPERM:
# SSL unknown protocol error
@@ -583,7 +585,7 @@ class IMAPServer:
reason = "Unknown SSL protocol connecting to host '%s' for "\
"repository '%s'. OpenSSL responded:\n%s"\
% (self.hostname, self.repos, e)
- raise OfflineImapError(reason, severity), None, exc_info()[2]
+ six.reraise(OfflineImapError(reason, severity), None, exc_info()[2])
elif isinstance(e, socket.error) and e.args[0] == errno.ECONNREFUSED:
# "Connection refused", can be a non-existing port, or an unauthorized
@@ -592,14 +594,14 @@ class IMAPServer:
"refused. Make sure you have the right host and port "\
"configured and that you are actually able to access the "\
"network."% (self.hostname, self.port, self.repos)
- raise OfflineImapError(reason, severity), None, exc_info()[2]
+ six.reraise(OfflineImapError(reason, severity), None, exc_info()[2])
# Could not acquire connection to the remote;
# socket.error(last_error) raised
if str(e)[:24] == "can't open socket; error":
- raise OfflineImapError("Could not connect to remote server '%s' "\
+ six.reraise(OfflineImapError("Could not connect to remote server '%s' "\
"for repository '%s'. Remote does not answer."
% (self.hostname, self.repos),
- OfflineImapError.ERROR.REPO), None, exc_info()[2]
+ OfflineImapError.ERROR.REPO), None, exc_info()[2])
else:
# re-raise all other errors
raise
diff --git a/offlineimap/repository/IMAP.py b/offlineimap/repository/IMAP.py
index 098300f..755f2ce 100644
--- a/offlineimap/repository/IMAP.py
+++ b/offlineimap/repository/IMAP.py
@@ -27,6 +27,8 @@ from offlineimap.folder.UIDMaps import MappedIMAPFolder
from offlineimap.threadutil import ExitNotifyThread
from offlineimap.utils.distro import get_os_sslcertfile, get_os_sslcertfile_searchpath
+import six
+
class IMAPRepository(BaseRepository):
def __init__(self, reposname, account):
@@ -107,9 +109,8 @@ class IMAPRepository(BaseRepository):
try:
host = self.localeval.eval(host)
except Exception as e:
- raise OfflineImapError("remotehosteval option for repository "
- "'%s' failed:\n%s"% (self, e), OfflineImapError.ERROR.REPO), \
- None, exc_info()[2]
+ six.reraise(OfflineImapError("remotehosteval option for repository "
+ "'%s' failed:\n%s"% (self, e), OfflineImapError.ERROR.REPO), None, exc_info()[2])
if host:
self._host = host
return self._host
diff --git a/offlineimap/repository/__init__.py b/offlineimap/repository/__init__.py
index 0fbbc13..e594e9d 100644
--- a/offlineimap/repository/__init__.py
+++ b/offlineimap/repository/__init__.py
@@ -17,6 +17,8 @@
from sys import exc_info
+import six
+
try:
from configparser import NoSectionError
except ImportError: #python2
@@ -68,16 +70,14 @@ class Repository(object):
except NoSectionError as e:
errstr = ("Could not find section '%s' in configuration. Required "
"for account '%s'." % ('Repository %s' % name, account))
- raise OfflineImapError(errstr, OfflineImapError.ERROR.REPO), \
- None, exc_info()[2]
+ six.reraise(OfflineImapError(errstr, OfflineImapError.ERROR.REPO), None, exc_info()[2])
try:
repo = typemap[repostype]
except KeyError:
errstr = "'%s' repository not supported for '%s' repositories."% \
(repostype, reqtype)
- raise OfflineImapError(errstr, OfflineImapError.ERROR.REPO), \
- None, exc_info()[2]
+ six.reraise(OfflineImapError(errstr, OfflineImapError.ERROR.REPO), None, exc_info()[2])
return repo(name, account)
--
2.8.2
More information about the OfflineIMAP-project
mailing list