Improve pylint score of gen modules to above 9

This commit is contained in:
Nick Hall 2016-01-10 15:40:52 +00:00
parent b8a38cd5e5
commit 177e30ee62
13 changed files with 1075 additions and 1019 deletions

View File

@ -17,12 +17,11 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# gen/__init__.py
"""
The gen module provides packages that are common to all gramps
interfaces (gui, cli and web).
"""
__all__ = [ "datehandler", "db", "display", "filters", "lib", "locale", "merge",
__all__ = ["datehandler", "db", "display", "filters", "lib", "merge",
"mime", "plug", "proxy", "simple", "utils"]

View File

@ -31,7 +31,7 @@ This package implements access to GRAMPS configuration.
# Gramps imports
#
#---------------------------------------------------------------
import os, sys
import os
import re
import logging
@ -40,10 +40,10 @@ import logging
# Gramps imports
#
#---------------------------------------------------------------
from .const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from .const import HOME_DIR, USER_HOME, VERSION_DIR
from .utils.configmanager import ConfigManager
from .const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#---------------------------------------------------------------
#
@ -154,13 +154,13 @@ register('behavior.welcome', 100)
register('behavior.web-search-url', 'http://google.com/#&q=%(text)s')
register('behavior.addons-url', "https://raw.githubusercontent.com/gramps-project/addons/master/gramps50")
register('export.proxy-order', [
["privacy", 0],
register('export.proxy-order',
[["privacy", 0],
["living", 0],
["person", 0],
["note", 0],
["reference", 0],
])
["reference", 0]]
)
register('geography.center-lon', 0.0)
register('geography.lock', False)
@ -383,11 +383,14 @@ if not os.path.exists(CONFIGMAN.filename):
# Perhaps addings specific list of versions to check
# -----------------------------------------
digits = str(int(match.groups()[0]) - i)
previous_grampsini = os.path.join(fullpath, "gramps" + str(digits), filename)
previous_grampsini = os.path.join(fullpath, "gramps" + digits,
filename)
if os.path.exists(previous_grampsini):
logging.warning("Importing old config file '%s'..." % previous_grampsini)
logging.warning("Importing old config file '%s'...",
previous_grampsini)
CONFIGMAN.load(previous_grampsini)
logging.warning("Done importing old config file '%s'" % previous_grampsini)
logging.warning("Done importing old config file '%s'",
previous_grampsini)
break
#---------------------------------------------------------------

View File

@ -41,16 +41,20 @@ import uuid
#-------------------------------------------------------------------------
from .git_revision import get_git_revision
from .constfunc import get_env_var
from gramps.version import VERSION, VERSION_TUPLE, major_version
from gramps.gen.utils.resourcepath import ResourcePath
from gramps.gen.utils.grampslocale import GrampsLocale
#-------------------------------------------------------------------------
#
# Gramps Version
# Gramps program name
#
#-------------------------------------------------------------------------
PROGRAM_NAME = "Gramps"
from gramps.version import VERSION, VERSION_TUPLE, major_version
#-------------------------------------------------------------------------
#
# Standard GRAMPS Websites
# Standard Gramps Websites
#
#-------------------------------------------------------------------------
URL_HOMEPAGE = "http://gramps-project.org/"
@ -160,7 +164,6 @@ else:
# Paths to data files.
#
#-------------------------------------------------------------------------
from gramps.gen.utils.resourcepath import ResourcePath
_resources = ResourcePath()
DATA_DIR = _resources.data_dir
IMAGE_DIR = _resources.image_dir
@ -203,7 +206,6 @@ ENV = {
# Init Localization
#
#-------------------------------------------------------------------------
from gramps.gen.utils.grampslocale import GrampsLocale
GRAMPS_LOCALE = GrampsLocale(localedir=_resources.locale_dir)
_ = GRAMPS_LOCALE.translation.sgettext
GTK_GETTEXT_DOMAIN = 'gtk30'

View File

@ -32,7 +32,6 @@ perform a translation on import, eg Gtk.
#------------------------------------------------------------------------
import platform
import sys
import ctypes
import os
#-------------------------------------------------------------------------
@ -87,9 +86,12 @@ def is_quartz():
"""
if mac():
try:
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
except:
except ImportError:
return False
return Gdk.Display.get_default().__class__.__name__.endswith("QuartzDisplay")
return False
@ -102,9 +104,12 @@ def has_display():
# in argv, and we might have unicode.
temp, sys.argv = sys.argv, sys.argv[:1]
try:
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
except:
except ImportError:
return False
try:
@ -146,7 +151,7 @@ def get_env_var(name, default=None):
environment variables. This routine does so using the native C
wide-character function.
'''
if not name or not name in os.environ:
if not name or name not in os.environ:
return default
return os.environ[name]

View File

@ -22,9 +22,21 @@
"""
Provide the database state class
"""
#------------------------------------------------------------------------
#
# Python modules
#
#------------------------------------------------------------------------
import sys
import os
import logging
#------------------------------------------------------------------------
#
# Gramps modules
#
#------------------------------------------------------------------------
from .db import DbReadBase
from .proxy.proxybase import ProxyDbBase
from .utils.callback import Callback
@ -35,7 +47,6 @@ from .config import config
# set up logging
#
#-------------------------------------------------------------------------
import logging
LOG = logging.getLogger(".dbstate")
class DbState(Callback):
@ -116,12 +127,15 @@ class DbState(Callback):
>>> dbstate.apply_proxy(gramps.gen.proxy.LivingProxyDb, 0)
>>> dbstate.apply_proxy(gramps.gen.proxy.PrivateProxyDb)
>>> from gramps.gen.filters.rules.person import IsDescendantOf, IsAncestorOf
>>> from gramps.gen.filters.rules.person import (IsDescendantOf,
IsAncestorOf)
>>> from gramps.gen.filters import GenericFilter
>>> filter = GenericFilter()
>>> filter.set_logical_op("or")
>>> filter.add_rule(IsDescendantOf([db.get_default_person().gramps_id, True]))
>>> filter.add_rule(IsAncestorOf([db.get_default_person().gramps_id, True]))
>>> filter.add_rule(IsDescendantOf([db.get_default_person().gramps_id,
True]))
>>> filter.add_rule(IsAncestorOf([db.get_default_person().gramps_id,
True]))
>>> dbstate.apply_proxy(gramps.gen.proxy.FilterProxyDb, filter)
"""
self.stack.append(self.db)
@ -140,7 +154,7 @@ class DbState(Callback):
self.db = self.stack.pop()
self.emit('database-changed', (self.db, ))
def make_database(self, id):
def make_database(self, plugin_id):
"""
Make a database, given a plugin id.
"""
@ -148,14 +162,14 @@ class DbState(Callback):
from .const import PLUGINS_DIR, USER_PLUGINS
pmgr = BasePluginManager.get_instance()
pdata = pmgr.get_plugin(id)
pdata = pmgr.get_plugin(plugin_id)
if not pdata:
# This might happen if using gramps from outside, and
# we haven't loaded plugins yet
pmgr.reg_plugins(PLUGINS_DIR, self, None)
pmgr.reg_plugins(USER_PLUGINS, self, None, load_on_reg=True)
pdata = pmgr.get_plugin(id)
pdata = pmgr.get_plugin(plugin_id)
if pdata:
if pdata.reset_system:
@ -225,7 +239,7 @@ class DbState(Callback):
if user is None:
user = User()
(name, ext) = os.path.splitext(os.path.basename(filename))
format = ext[1:].lower()
extension = ext[1:].lower()
import_list = pmgr.get_reg_importers()
if import_list == []:
# This might happen if using gramps from outside, and
@ -234,12 +248,11 @@ class DbState(Callback):
pmgr.reg_plugins(USER_PLUGINS, self, None, load_on_reg=True)
import_list = pmgr.get_reg_importers()
for pdata in import_list:
if format == pdata.extension:
if extension == pdata.extension:
mod = pmgr.load_plugin(pdata)
if not mod:
for item in pmgr.get_fail_list():
name, error_tuple, pdata = item
# (filename, (exception-type, exception, traceback), pdata)
etype, exception, traceback = error_tuple
print("ERROR:", name, exception)
return False
@ -261,7 +274,7 @@ class DbState(Callback):
LOG.info("reset_modules!")
# First, clear out old modules:
for key in list(sys.modules.keys()):
del(sys.modules[key])
del sys.modules[key]
# Next, restore previous:
for key in self._modules:
sys.modules[key] = self._modules[key]

View File

@ -19,18 +19,25 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
Find the latest git revision.
"""
import subprocess
def get_git_revision(path=""):
"""
Return the short commit hash of the latest commit.
"""
stdout = ""
command = "git log -1 --format=%h"
try:
p = subprocess.Popen(
proc = subprocess.Popen(
"{} \"{}\"".format(command, path),
shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
except:
(stdout, stderr) = proc.communicate()
except OSError:
return "" # subprocess failed
# subprocess worked
if stdout and len(stdout) > 0: # has output

View File

@ -28,15 +28,14 @@
#-------------------------------------------------------------------------
import os
import time
import io
import logging
from xml.parsers.expat import ParserCreate
from xml.parsers.expat import ParserCreate, ExpatError
try:
import fcntl
use_lock = True
except:
use_lock = False
USE_LOCK = True
except ImportError:
USE_LOCK = False
from gramps.gen.const import HOME_DIR, GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
@ -65,21 +64,39 @@ class RecentItem(object):
self.time = t
def set_path(self, val):
"""
Set the file path.
"""
self.path = val
def get_path(self):
"""
Get the file path.
"""
return self.path
def set_name(self, val):
"""
Set the file name.
"""
self.name = val
def get_name(self):
"""
Get the file name.
"""
return self.name
def set_time(self, val):
"""
Set the file timestamp.
"""
self.time = int(val)
def get_time(self):
"""
Get the file timestamp.
"""
return self.time
def __eq__(self, other_item):
@ -100,10 +117,6 @@ class RecentItem(object):
def __ge__(self, other_item):
return self.time >= other_item.time
## Python 3, no __cmp__
## def __cmp__(self, other_item):
## return cmp(self.time, other_item.time)
#-------------------------------------------------------------------------
#
# RecentFiles
@ -119,6 +132,9 @@ class RecentFiles(object):
self.gramps_recent_files = gramps_parser.get()
def add(self, item2add):
"""
Add a file to the recent files list.
"""
# First we need to walk the existing items to see
# if our item is already there
for item in self.gramps_recent_files:
@ -131,9 +147,10 @@ class RecentFiles(object):
# so simply inserting a new item in the beginning
self.gramps_recent_files.insert(0, item2add)
def rename_filename(self, filename, new_filename):
"""
Rename a file in the recent files list.
"""
# First we need to walk the existing items to see
# if our item is already there
found = False
@ -146,6 +163,9 @@ class RecentFiles(object):
self.gramps_recent_files[index].set_name(new_filename)
def remove_filename(self, filename):
"""
Remove a file from the recent files list.
"""
# First we need to walk the existing items to see
# if our item is already there
found = False
@ -157,8 +177,10 @@ class RecentFiles(object):
if found:
self.gramps_recent_files.pop(index)
def check_if_recent(self, filename):
"""
Check if a file is present in the recent files list.
"""
# First we need to walk the existing items to see
# if our item is already there
found = False
@ -174,18 +196,20 @@ class RecentFiles(object):
Attempt saving into XML.
The trick is not to fail under any circumstances.
"""
fname = os.path.expanduser(GRAMPS_FILENAME)
try:
self.do_save()
except:
pass
self.do_save(fname)
except IOError as err:
logging.warning(
_("Unable to save list of recent DBs file {fname}: {error}"
).format(fname=fname, error=err))
def do_save(self):
def do_save(self, fname):
"""
Saves the current Gramps RecentFiles collection to the associated file.
"""
with open(os.path.expanduser(GRAMPS_FILENAME), 'w', encoding='utf8') \
as xml_file:
if use_lock:
with open(fname, 'w', encoding='utf8') as xml_file:
if USE_LOCK:
fcntl.lockf(xml_file, fcntl.LOCK_EX)
xml_file.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
xml_file.write('<RecentFiles>\n')
@ -195,9 +219,12 @@ class RecentFiles(object):
if index > MAX_GRAMPS_ITEMS:
break
xml_file.write(' <RecentItem>\n')
xml_file.write(' <Path><![CDATA[%s]]></Path>\n' % item.get_path())
xml_file.write(' <Name><![CDATA[%s]]></Name>\n' % item.get_name())
xml_file.write(' <Timestamp>%d</Timestamp>\n' % item.get_time())
xml_file.write(' <Path><![CDATA[%s]]></Path>\n' %
item.get_path())
xml_file.write(' <Name><![CDATA[%s]]></Name>\n' %
item.get_name())
xml_file.write(' <Timestamp>%d</Timestamp>\n' %
item.get_time())
xml_file.write(' </RecentItem>\n')
xml_file.write('</RecentFiles>\n')
@ -215,6 +242,8 @@ class RecentParser(object):
def __init__(self):
self.recent_files = []
self.tlist = []
self.item = None
fname = os.path.expanduser(GRAMPS_FILENAME)
if not os.path.exists(fname):
@ -222,37 +251,45 @@ class RecentParser(object):
try:
with open(fname, "rb") as xml_file:
if use_lock:
if USE_LOCK:
fcntl.lockf(xml_file, fcntl.LOCK_SH)
p = ParserCreate()
p.StartElementHandler = self.startElement
p.EndElementHandler = self.endElement
p.CharacterDataHandler = self.characters
p.ParseFile(xml_file)
parser = ParserCreate()
parser.StartElementHandler = self.start_element
parser.EndElementHandler = self.end_element
parser.CharacterDataHandler = self.characters
parser.ParseFile(xml_file)
# all advisory locks on a file are released on close
except IOError as err:
logging.warning(
_("Unable to open list of recent DBs file {fname}: {error}"
).format(fname=fname, error=err))
except Exception as err:
except ExpatError as err:
logging.error(
_("Error parsing list of recent DBs from file {fname}: {error}.\n"
"This might indicate a damage to your files.\n"
_("Error parsing list of recent DBs from file {fname}: "
"{error}.\nThis might indicate a damage to your files.\n"
"If you're sure there is no problem with other files, "
"delete it, and restart Gramps."
).format(fname=fname, error=err))
def get(self):
"""
Return a list of recent files.
"""
return self.recent_files
def startElement(self,tag,attrs):
def start_element(self, tag, attrs):
"""
Handler for XML start element.
"""
self.tlist = []
if tag == "RecentItem":
self.item = RecentItem()
def endElement(self,tag):
def end_element(self, tag):
"""
Handler for XML end element.
"""
text = ''.join(self.tlist)
if tag == "RecentItem":
@ -266,6 +303,9 @@ class RecentParser(object):
self.item.set_time(int(text))
def characters(self, data):
"""
Handler for XML character data.
"""
self.tlist.append(data)
#-------------------------------------------------------------------------
@ -275,9 +315,8 @@ class RecentParser(object):
#-------------------------------------------------------------------------
def recent_files(filename, name):
"""
Add an entry to both GNOME and Gramps recent-items storages.
Add an entry to the Gramps recent items list.
"""
the_time = int(time.time())
gramps_rf = RecentFiles()
gramps_item = RecentItem(
@ -288,16 +327,24 @@ def recent_files(filename, name):
gramps_rf.save()
def remove_filename(filename):
"""
Remove an entry from the Gramps recent items list.
"""
gramps_rf = RecentFiles()
gramps_rf.remove_filename(filename)
gramps_rf.save()
def rename_filename(filename, new_filename):
"""
Rename an entry in the Gramps recent items list.
"""
gramps_rf = RecentFiles()
gramps_rf.rename_filename(filename, new_filename)
gramps_rf.save()
def check_if_recent(filename):
"""
Check if an entry is present in Gramps recent items list.
"""
gramps_rf = RecentFiles()
return gramps_rf.check_if_recent(filename)

File diff suppressed because it is too large Load Diff

View File

@ -114,8 +114,8 @@ class Sort(object):
return glocale.sort_key(name1)
## def by_birthdate(self, first_id, second_id):
## """Sort routine for comparing two people by birth dates. If the birth dates
## are equal, sorts by name"""
## """Sort routine for comparing two people by birth dates. If the birth
## dates are equal, sorts by name"""
## first = self.database.get_person_from_handle(first_id)
## second = self.database.get_person_from_handle(second_id)
##
@ -218,7 +218,8 @@ class Sort(object):
## return 0
## evt_a = self.database.get_event_from_handle(a_id)
## evt_b = self.database.get_event_from_handle(b_id)
## return glocale.strcoll(evt_a.get_description(), evt_b.get_description())
## return glocale.strcoll(evt_a.get_description(),
## evt_b.get_description())
def by_event_description_key(self, a_id):
"""Sort routine for comparing two events by their descriptions. """
@ -269,5 +270,5 @@ class Sort(object):
"""Sort routine for comparing two media objects by their title. """
if not a_id:
return False
a = self.database.get_object_from_handle(a_id)
return glocale.sort_key(a.desc)
obj_a = self.database.get_object_from_handle(a_id)
return glocale.sort_key(obj_a.desc)

View File

@ -46,8 +46,8 @@ TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ',
def soundex(strval):
"Return the soundex value to a string argument."
strval = unicodedata.normalize('NFKD',
str(strval.upper().strip())).encode('ASCII', 'ignore')
strval = unicodedata.normalize(
'NFKD', str(strval.upper().strip())).encode('ASCII', 'ignore')
if not strval:
return "Z000"
strval = strval.decode('ASCII', 'ignore')

View File

@ -34,9 +34,12 @@ class TestUser_prompt(unittest.TestCase):
def setUp(self):
self.user = user.User()
def test_returns_False(self):
assert not self.user.prompt(
TestUser.TITLE, TestUser.MSG, TestUser.ACCEPT, TestUser.REJECT)
def test_not_implemented(self):
self.assertRaises(NotImplementedError, self.user.prompt,
TestUser.TITLE,
TestUser.MSG,
TestUser.ACCEPT,
TestUser.REJECT)
if __name__ == "__main__":
unittest.main()

View File

@ -35,6 +35,7 @@ import time
import collections
import logging
_LOG = logging.getLogger(".gen")
#-------------------------------------------------------------------------
#
# Callback updater
@ -53,31 +54,47 @@ class UpdateCallback(object):
:param interval: number of seconds at most between the updates
:type interval: int
"""
if isinstance(callback, collections.Callable): # callback is really callable
if isinstance(callback, collections.Callable):
# callback is really callable
self.update = self.update_real
self.callback = callback
self.interval = interval
self.reset()
else:
self.update = self.update_empty
self.count = 0
self.oldval = 0
self.oldtime = 0
self.text = ""
self.total = 1
def reset(self, text=""):
"""
Reset the count to zero.
"""
self.count = 0
self.oldval = 0
self.oldtime = 0
self.text = text
def set_total(self, total):
"""
Set the total.
"""
self.total = total
if self.total == 0:
_LOG.warning('UpdateCallback with total == 0 created')
self.total = 1
def update_empty(self, count=None):
"""
Dummy update used when no callback is specified.
"""
pass
def update_real(self, count=None):
"""
Called when the count is updated.
"""
self.count += 1
if not count:
count = self.count

View File

@ -18,12 +18,13 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import sys
from contextlib import contextmanager
"""
The User class provides basic interaction with the user.
"""
import sys
from contextlib import contextmanager
class User():
"""
This class provides a means to interact with the user in an abstract way.
@ -53,7 +54,7 @@ class User():
:type steps: int
:returns: none
"""
pass
raise NotImplementedError
def step_progress(self):
"""
@ -61,7 +62,7 @@ class User():
Don't use this method directly, use progress instead.
"""
pass
raise NotImplementedError
def callback(self, percentage, text=None):
"""
@ -87,7 +88,7 @@ class User():
Don't use this method directly, use progress instead.
"""
pass
raise NotImplementedError
# Context-manager wrapper of the begin/step/end_progress above
@contextmanager
@ -130,7 +131,7 @@ class User():
:returns: the user's answer to the question
:rtype: bool
"""
return False
raise NotImplementedError
def warn(self, title, warning=""):
"""
@ -142,7 +143,7 @@ class User():
:type warning: str
:returns: none
"""
pass
raise NotImplementedError
def notify_error(self, title, error=""):
"""
@ -154,7 +155,7 @@ class User():
:type error: str
:returns: none
"""
pass
raise NotImplementedError
def notify_db_error(self, error):
"""
@ -164,10 +165,10 @@ class User():
:type error: str
:returns: none
"""
pass
raise NotImplementedError
def info(self, msg1, infotext, parent=None, monospaced=False):
"""
Displays information to the user
"""
pass
raise NotImplementedError