Reformat offlineimap/init.py

Add some spaces, remove lines,... now format is better (lintian).
This commit is contained in:
Rodolfo García Peñas (kix) 2020-08-29 20:21:07 +02:00
parent 2969f36663
commit 0e477ca9cc

View File

@ -38,7 +38,6 @@ from offlineimap.utils import stacktrace
from offlineimap.repository import Repository from offlineimap.repository import Repository
from offlineimap.folder.IMAP import MSGCOPY_NAMESPACE from offlineimap.folder.IMAP import MSGCOPY_NAMESPACE
ACCOUNT_LIMITED_THREAD_NAME = 'MAX_ACCOUNTS' ACCOUNT_LIMITED_THREAD_NAME = 'MAX_ACCOUNTS'
PYTHON_VERSION = sys.version.split(' ')[0] PYTHON_VERSION = sys.version.split(' ')[0]
@ -46,21 +45,21 @@ PYTHON_VERSION = sys.version.split(' ')[0]
def syncitall(list_accounts, config): def syncitall(list_accounts, config):
"""The target when in multithreading mode for running accounts threads.""" """The target when in multithreading mode for running accounts threads."""
threads = threadutil.accountThreads() # The collection of accounts threads. threads = threadutil.accountThreads() # The collection of accounts threads.
for accountname in list_accounts: for accountname in list_accounts:
# Start a new thread per account and store it in the collection. # Start a new thread per account and store it in the collection.
account = accounts.SyncableAccount(config, accountname) account = accounts.SyncableAccount(config, accountname)
thread = threadutil.InstanceLimitedThread( thread = threadutil.InstanceLimitedThread(
ACCOUNT_LIMITED_THREAD_NAME, ACCOUNT_LIMITED_THREAD_NAME,
target = account.syncrunner, target=account.syncrunner,
name = "Account sync %s"% accountname name="Account sync %s" % accountname
) )
thread.setDaemon(True) thread.setDaemon(True)
# The add() method expects a started thread. # The add() method expects a started thread.
thread.start() thread.start()
threads.add(thread) threads.add(thread)
# Wait for the threads to finish. # Wait for the threads to finish.
threads.wait() # Blocks until all accounts are processed. threads.wait() # Blocks until all accounts are processed.
class OfflineImap(object): class OfflineImap(object):
@ -73,12 +72,10 @@ class OfflineImap(object):
""" """
def get_env_info(self): def get_env_info(self):
info = "imaplib2 v%s (%s), Python v%s"% ( info = "imaplib2 v%s (%s), Python v%s" % (imaplib.__version__, imaplib.DESC, PYTHON_VERSION)
imaplib.__version__, imaplib.DESC, PYTHON_VERSION
)
try: try:
import ssl import ssl
info = "%s, %s"% (info, ssl.OPENSSL_VERSION) info = "%s, %s" % (info, ssl.OPENSSL_VERSION)
except: except:
pass pass
return info return info
@ -103,97 +100,97 @@ class OfflineImap(object):
def __parse_cmd_options(self): def __parse_cmd_options(self):
parser = OptionParser( parser = OptionParser(
version=offlineimap.__version__, version=offlineimap.__version__,
description="%s.\n\n%s"% (offlineimap.__copyright__, description="%s.\n\n%s" % (offlineimap.__copyright__,
offlineimap.__license__) offlineimap.__license__)
) )
parser.add_option("-V", parser.add_option("-V",
action="store_true", dest="version", action="store_true", dest="version",
default=False, default=False,
help="show full version infos") help="show full version infos")
parser.add_option("--dry-run", parser.add_option("--dry-run",
action="store_true", dest="dryrun", action="store_true", dest="dryrun",
default=False, default=False,
help="dry run mode") help="dry run mode")
parser.add_option("--info", parser.add_option("--info",
action="store_true", dest="diagnostics", action="store_true", dest="diagnostics",
default=False, default=False,
help="output information on the configured email repositories") help="output information on the configured email repositories")
parser.add_option("-1", parser.add_option("-1",
action="store_true", dest="singlethreading", action="store_true", dest="singlethreading",
default=False, default=False,
help="(the number one) disable all multithreading operations") help="(the number one) disable all multithreading operations")
parser.add_option("-P", dest="profiledir", metavar="DIR", parser.add_option("-P", dest="profiledir", metavar="DIR",
help="sets OfflineIMAP into profile mode.") help="sets OfflineIMAP into profile mode.")
parser.add_option("-a", dest="accounts", parser.add_option("-a", dest="accounts",
metavar="account1[,account2[,...]]", metavar="account1[,account2[,...]]",
help="list of accounts to sync") help="list of accounts to sync")
parser.add_option("-c", dest="configfile", metavar="FILE", parser.add_option("-c", dest="configfile", metavar="FILE",
default=None, default=None,
help="specifies a configuration file to use") help="specifies a configuration file to use")
parser.add_option("-d", dest="debugtype", parser.add_option("-d", dest="debugtype",
metavar="type1[,type2[,...]]", metavar="type1[,type2[,...]]",
help="enables debugging for OfflineIMAP " help="enables debugging for OfflineIMAP "
" (types: imap, maildir, thread)") " (types: imap, maildir, thread)")
parser.add_option("-l", dest="logfile", metavar="FILE", parser.add_option("-l", dest="logfile", metavar="FILE",
help="log to FILE") help="log to FILE")
parser.add_option("-s", parser.add_option("-s",
action="store_true", dest="syslog", action="store_true", dest="syslog",
default=False, default=False,
help="log to syslog") help="log to syslog")
parser.add_option("-f", dest="folders", parser.add_option("-f", dest="folders",
metavar="folder1[,folder2[,...]]", metavar="folder1[,folder2[,...]]",
help="only sync the specified folders") help="only sync the specified folders")
parser.add_option("-k", dest="configoverride", parser.add_option("-k", dest="configoverride",
action="append", action="append",
metavar="[section:]option=value", metavar="[section:]option=value",
help="override configuration file option") help="override configuration file option")
parser.add_option("-o", parser.add_option("-o",
action="store_true", dest="runonce", action="store_true", dest="runonce",
default=False, default=False,
help="run only once (ignore autorefresh)") help="run only once (ignore autorefresh)")
parser.add_option("-q", parser.add_option("-q",
action="store_true", dest="quick", action="store_true", dest="quick",
default=False, default=False,
help="run only quick synchronizations (don't update flags)") help="run only quick synchronizations (don't update flags)")
parser.add_option("-u", dest="interface", parser.add_option("-u", dest="interface",
help="specifies an alternative user interface" help="specifies an alternative user interface"
" (quiet, basic, syslog, ttyui, blinkenlights, machineui)") " (quiet, basic, syslog, ttyui, blinkenlights, machineui)")
parser.add_option("--delete-folder", dest="deletefolder", parser.add_option("--delete-folder", dest="deletefolder",
default=None, default=None,
metavar="FOLDERNAME", metavar="FOLDERNAME",
help="Delete a folder (on the remote repository)") help="Delete a folder (on the remote repository)")
parser.add_option("--migrate-fmd5-using-nametrans", parser.add_option("--migrate-fmd5-using-nametrans",
action="store_true", dest="migrate_fmd5", default=False, action="store_true", dest="migrate_fmd5", default=False,
help="migrate FMD5 hashes from versions prior to 6.3.5") help="migrate FMD5 hashes from versions prior to 6.3.5")
parser.add_option("--mbnames-prune", parser.add_option("--mbnames-prune",
action="store_true", dest="mbnames_prune", default=False, action="store_true", dest="mbnames_prune", default=False,
help="remove mbnames entries for accounts not in accounts") help="remove mbnames entries for accounts not in accounts")
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
glob.set_options(options) glob.set_options(options)
if options.version: if options.version:
print(("offlineimap v%s, %s"% ( print(("offlineimap v%s, %s" % (
offlineimap.__version__, self.get_env_info()) offlineimap.__version__, self.get_env_info())
)) ))
sys.exit(0) sys.exit(0)
# Read in configuration file. # Read in configuration file.
@ -214,7 +211,7 @@ class OfflineImap(object):
config = CustomConfigParser() config = CustomConfigParser()
if not os.path.exists(configfilename): if not os.path.exists(configfilename):
# TODO, initialize and make use of chosen ui for logging # TODO, initialize and make use of chosen ui for logging
logging.error(" *** Config file '%s' does not exist; aborting!"% logging.error(" *** Config file '%s' does not exist; aborting!" %
configfilename) configfilename)
sys.exit(1) sys.exit(1)
config.read(configfilename) config.read(configfilename)
@ -227,13 +224,13 @@ class OfflineImap(object):
options.singlethreading = True options.singlethreading = True
if os.path.exists(options.profiledir): if os.path.exists(options.profiledir):
# TODO, make use of chosen ui for logging # TODO, make use of chosen ui for logging
logging.warn("Profile mode: Directory '%s' already exists!"% logging.warn("Profile mode: Directory '%s' already exists!" %
options.profiledir) options.profiledir)
else: else:
os.mkdir(options.profiledir) os.mkdir(options.profiledir)
# TODO, make use of chosen ui for logging # TODO, make use of chosen ui for logging
logging.warn("Profile mode: Potentially large data will be " logging.warn("Profile mode: Potentially large data will be "
"created in '%s'"% options.profiledir) "created in '%s'" % options.profiledir)
# Override a config value. # Override a config value.
if options.configoverride: if options.configoverride:
@ -255,9 +252,9 @@ class OfflineImap(object):
ui_type = ui_type.split('.')[-1] ui_type = ui_type.split('.')[-1]
# TODO, make use of chosen ui for logging # TODO, make use of chosen ui for logging
logging.warning('Using old interface name, consider using one ' logging.warning('Using old interface name, consider using one '
'of %s'% ', '.join(list(UI_LIST.keys()))) 'of %s' % ', '.join(list(UI_LIST.keys())))
if options.diagnostics: if options.diagnostics:
ui_type = 'ttyui' # Enforce this UI for --info. ui_type = 'ttyui' # Enforce this UI for --info.
# dry-run? Set [general]dry-run=True. # dry-run? Set [general]dry-run=True.
if options.dryrun: if options.dryrun:
@ -268,8 +265,8 @@ class OfflineImap(object):
# Create the ui class. # Create the ui class.
self.ui = UI_LIST[ui_type.lower()](config) self.ui = UI_LIST[ui_type.lower()](config)
except KeyError: except KeyError:
logging.error("UI '%s' does not exist, choose one of: %s"% logging.error("UI '%s' does not exist, choose one of: %s" %
(ui_type, ', '.join(list(UI_LIST.keys())))) (ui_type, ', '.join(list(UI_LIST.keys()))))
sys.exit(1) sys.exit(1)
setglobalui(self.ui) setglobalui(self.ui)
@ -315,12 +312,12 @@ class OfflineImap(object):
# Custom folder list specified? # Custom folder list specified?
if options.folders: if options.folders:
foldernames = options.folders.split(",") foldernames = options.folders.split(",")
folderfilter = "lambda f: f in %s"% foldernames folderfilter = "lambda f: f in %s" % foldernames
folderincludes = "[]" folderincludes = "[]"
for accountname in accounts.getaccountlist(config): for accountname in accounts.getaccountlist(config):
account_section = 'Account ' + accountname account_section = 'Account ' + accountname
remote_repo_section = 'Repository ' + \ remote_repo_section = 'Repository ' + \
config.get(account_section, 'remoterepository') config.get(account_section, 'remoterepository')
config.set(remote_repo_section, "folderfilter", folderfilter) config.set(remote_repo_section, "folderfilter", folderfilter)
config.set(remote_repo_section, "folderincludes", config.set(remote_repo_section, "folderincludes",
folderincludes) folderincludes)
@ -335,13 +332,13 @@ class OfflineImap(object):
threadutil.initInstanceLimit( threadutil.initInstanceLimit(
ACCOUNT_LIMITED_THREAD_NAME, ACCOUNT_LIMITED_THREAD_NAME,
config.getdefaultint('general', 'maxsyncaccounts', 1) config.getdefaultint('general', 'maxsyncaccounts', 1)
) )
for reposname in config.getsectionlist('Repository'): for reposname in config.getsectionlist('Repository'):
# Limit the number of threads. Limitation on usage is handled at the # Limit the number of threads. Limitation on usage is handled at the
# imapserver level. # imapserver level.
for namespace in [accounts.FOLDER_NAMESPACE + reposname, for namespace in [accounts.FOLDER_NAMESPACE + reposname,
MSGCOPY_NAMESPACE + reposname]: MSGCOPY_NAMESPACE + reposname]:
if options.singlethreading: if options.singlethreading:
threadutil.initInstanceLimit(namespace, 1) threadutil.initInstanceLimit(namespace, 1)
else: else:
@ -350,7 +347,7 @@ class OfflineImap(object):
config.getdefaultint( config.getdefaultint(
'Repository ' + reposname, 'Repository ' + reposname,
'maxconnections', 2) 'maxconnections', 2)
) )
self.config = config self.config = config
return (options, args) return (options, args)
@ -403,9 +400,9 @@ class OfflineImap(object):
if accountname in allaccounts: if accountname in allaccounts:
activeaccounts.append(accountname) activeaccounts.append(accountname)
else: else:
errormsg = "Valid accounts are: %s"% ( errormsg = "Valid accounts are: %s" % (
", ".join(allaccounts)) ", ".join(allaccounts))
self.ui.error("The account '%s' does not exist"% accountname) self.ui.error("The account '%s' does not exist" % accountname)
if len(activeaccounts) < 1: if len(activeaccounts) < 1:
errormsg = "No accounts are defined!" errormsg = "No accounts are defined!"
@ -431,8 +428,8 @@ class OfflineImap(object):
accounts.Account.set_abort_event(self.config, 2) accounts.Account.set_abort_event(self.config, 2)
elif sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): elif sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
# tell each account to ABORT ASAP (ctrl-c) # tell each account to ABORT ASAP (ctrl-c)
getglobalui().warn("Preparing to shutdown after sync (this may "\ getglobalui().warn("Preparing to shutdown after sync (this may " \
"take some time), press CTRL-C three "\ "take some time), press CTRL-C three " \
"times to shutdown immediately") "times to shutdown immediately")
accounts.Account.set_abort_event(self.config, 3) accounts.Account.set_abort_event(self.config, 3)
if 'thread' in self.ui.debuglist: if 'thread' in self.ui.debuglist:
@ -470,7 +467,7 @@ class OfflineImap(object):
target=syncitall, target=syncitall,
name='Sync Runner', name='Sync Runner',
args=(activeaccounts, self.config,) args=(activeaccounts, self.config,)
) )
# Special exit message for the monitor to stop looping. # Special exit message for the monitor to stop looping.
t.exit_message = threadutil.STOP_MONITOR t.exit_message = threadutil.STOP_MONITOR
t.start() t.start()
@ -495,7 +492,7 @@ class OfflineImap(object):
for accountname in list_accounts: for accountname in list_accounts:
account = accounts.SyncableAccount(self.config, accountname) account = accounts.SyncableAccount(self.config, accountname)
threading.currentThread().name = \ threading.currentThread().name = \
"Account sync %s"% account.getname() "Account sync %s" % account.getname()
if not profiledir: if not profiledir:
account.syncrunner() account.syncrunner()
# Profile mode. # Profile mode.
@ -512,10 +509,10 @@ class OfflineImap(object):
from datetime import datetime from datetime import datetime
dt = datetime.now().strftime('%Y%m%d%H%M%S') dt = datetime.now().strftime('%Y%m%d%H%M%S')
prof.dump_stats(os.path.join( prof.dump_stats(os.path.join(
profiledir, "%s_%s.prof"% (dt, account.getname()))) profiledir, "%s_%s.prof" % (dt, account.getname())))
def __serverdiagnostics(self, options): def __serverdiagnostics(self, options):
self.ui.info(" imaplib2: %s (%s)"% (imaplib.__version__, imaplib.DESC)) self.ui.info(" imaplib2: %s (%s)" % (imaplib.__version__, imaplib.DESC))
for accountname in self._get_activeaccounts(options): for accountname in self._get_activeaccounts(options):
account = accounts.Account(self.config, accountname) account = accounts.Account(self.config, accountname)
account.serverdiagnostics() account.serverdiagnostics()