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 # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 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 The gen module provides packages that are common to all gramps
interfaces (gui, cli and web). 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" ] "mime", "plug", "proxy", "simple", "utils"]

View File

@ -31,7 +31,7 @@ This package implements access to GRAMPS configuration.
# Gramps imports # Gramps imports
# #
#--------------------------------------------------------------- #---------------------------------------------------------------
import os, sys import os
import re import re
import logging import logging
@ -40,10 +40,10 @@ import logging
# Gramps imports # Gramps imports
# #
#--------------------------------------------------------------- #---------------------------------------------------------------
from .const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from .const import HOME_DIR, USER_HOME, VERSION_DIR from .const import HOME_DIR, USER_HOME, VERSION_DIR
from .utils.configmanager import ConfigManager from .utils.configmanager import ConfigManager
from .const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#--------------------------------------------------------------- #---------------------------------------------------------------
# #
@ -134,7 +134,7 @@ register('behavior.check-for-update-types', ["new"])
register('behavior.last-check-for-updates', "1970/01/01") register('behavior.last-check-for-updates', "1970/01/01")
register('behavior.previously-seen-updates', []) register('behavior.previously-seen-updates', [])
register('behavior.do-not-show-previously-seen-updates', True) register('behavior.do-not-show-previously-seen-updates', True)
register('behavior.database-path', os.path.join( HOME_DIR, 'grampsdb')) register('behavior.database-path', os.path.join(HOME_DIR, 'grampsdb'))
register('behavior.database-backend', 'bsddb') register('behavior.database-backend', 'bsddb')
register('behavior.date-about-range', 50) register('behavior.date-about-range', 50)
register('behavior.date-after-range', 50) register('behavior.date-after-range', 50)
@ -154,13 +154,13 @@ register('behavior.welcome', 100)
register('behavior.web-search-url', 'http://google.com/#&q=%(text)s') 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('behavior.addons-url', "https://raw.githubusercontent.com/gramps-project/addons/master/gramps50")
register('export.proxy-order', [ register('export.proxy-order',
["privacy", 0], [["privacy", 0],
["living", 0], ["living", 0],
["person", 0], ["person", 0],
["note", 0], ["note", 0],
["reference", 0], ["reference", 0]]
]) )
register('geography.center-lon', 0.0) register('geography.center-lon', 0.0)
register('geography.lock', False) register('geography.lock', False)
@ -365,7 +365,7 @@ if not os.path.exists(CONFIGMAN.filename):
# read it in old style: # read it in old style:
logging.warning("Importing old key file 'keys.ini'...") logging.warning("Importing old key file 'keys.ini'...")
CONFIGMAN.load(os.path.join(HOME_DIR, "keys.ini"), CONFIGMAN.load(os.path.join(HOME_DIR, "keys.ini"),
oldstyle=True) oldstyle=True)
logging.warning("Done importing old key file 'keys.ini'") logging.warning("Done importing old key file 'keys.ini'")
# other version upgrades here... # other version upgrades here...
# check previous version of gramps: # check previous version of gramps:
@ -383,11 +383,14 @@ if not os.path.exists(CONFIGMAN.filename):
# Perhaps addings specific list of versions to check # Perhaps addings specific list of versions to check
# ----------------------------------------- # -----------------------------------------
digits = str(int(match.groups()[0]) - i) 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): 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) 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 break
#--------------------------------------------------------------- #---------------------------------------------------------------

View File

@ -41,23 +41,27 @@ import uuid
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from .git_revision import get_git_revision from .git_revision import get_git_revision
from .constfunc import get_env_var from .constfunc import get_env_var
#-------------------------------------------------------------------------
#
# Gramps Version
#
#-------------------------------------------------------------------------
PROGRAM_NAME = "Gramps"
from gramps.version import VERSION, VERSION_TUPLE, major_version from gramps.version import VERSION, VERSION_TUPLE, major_version
from gramps.gen.utils.resourcepath import ResourcePath
from gramps.gen.utils.grampslocale import GrampsLocale
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
# Standard GRAMPS Websites # Gramps program name
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
URL_HOMEPAGE = "http://gramps-project.org/" PROGRAM_NAME = "Gramps"
#-------------------------------------------------------------------------
#
# Standard Gramps Websites
#
#-------------------------------------------------------------------------
URL_HOMEPAGE = "http://gramps-project.org/"
URL_MAILINGLIST = "http://sourceforge.net/mail/?group_id=25770" URL_MAILINGLIST = "http://sourceforge.net/mail/?group_id=25770"
URL_BUGHOME = "http://bugs.gramps-project.org" URL_BUGHOME = "http://bugs.gramps-project.org"
URL_BUGTRACKER = "http://bugs.gramps-project.org/bug_report_page.php" URL_BUGTRACKER = "http://bugs.gramps-project.org/bug_report_page.php"
URL_WIKISTRING = "http://gramps-project.org/wiki/index.php?title=" URL_WIKISTRING = "http://gramps-project.org/wiki/index.php?title="
URL_MANUAL_PAGE = "Gramps_%s_Wiki_Manual" % major_version URL_MANUAL_PAGE = "Gramps_%s_Wiki_Manual" % major_version
URL_MANUAL_DATA = '%s_-_Entering_and_editing_data:_detailed' % URL_MANUAL_PAGE URL_MANUAL_DATA = '%s_-_Entering_and_editing_data:_detailed' % URL_MANUAL_PAGE
URL_MANUAL_SECT1 = '%s_-_part_1' % URL_MANUAL_DATA URL_MANUAL_SECT1 = '%s_-_part_1' % URL_MANUAL_DATA
@ -65,7 +69,7 @@ URL_MANUAL_SECT2 = '%s_-_part_2' % URL_MANUAL_DATA
URL_MANUAL_SECT3 = '%s_-_part_3' % URL_MANUAL_DATA URL_MANUAL_SECT3 = '%s_-_part_3' % URL_MANUAL_DATA
WIKI_FAQ = "FAQ" WIKI_FAQ = "FAQ"
WIKI_KEYBINDINGS = "Gramps_%s_Wiki_Manual_-_Keybindings" % major_version WIKI_KEYBINDINGS = "Gramps_%s_Wiki_Manual_-_Keybindings" % major_version
WIKI_EXTRAPLUGINS= "%s_Addons" % major_version WIKI_EXTRAPLUGINS = "%s_Addons" % major_version
WIKI_EXTRAPLUGINS_RAWDATA = "Plugins%s&action=raw" % major_version WIKI_EXTRAPLUGINS_RAWDATA = "Plugins%s&action=raw" % major_version
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
@ -73,13 +77,13 @@ WIKI_EXTRAPLUGINS_RAWDATA = "Plugins%s&action=raw" % major_version
# Mime Types # Mime Types
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
APP_FAMTREE = 'x-directory/normal' APP_FAMTREE = 'x-directory/normal'
APP_GRAMPS = "application/x-gramps" APP_GRAMPS = "application/x-gramps"
APP_GRAMPS_XML = "application/x-gramps-xml" APP_GRAMPS_XML = "application/x-gramps-xml"
APP_GEDCOM = "application/x-gedcom" APP_GEDCOM = "application/x-gedcom"
APP_GRAMPS_PKG = "application/x-gramps-package" APP_GRAMPS_PKG = "application/x-gramps-package"
APP_GENEWEB = "application/x-geneweb" APP_GENEWEB = "application/x-geneweb"
APP_VCARD = ["text/x-vcard", "text/x-vcalendar"] APP_VCARD = ["text/x-vcard", "text/x-vcalendar"]
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -102,19 +106,19 @@ else:
HOME_DIR = os.path.join(USER_HOME, '.gramps') HOME_DIR = os.path.join(USER_HOME, '.gramps')
VERSION_DIR = os.path.join( VERSION_DIR = os.path.join(
HOME_DIR, "gramps%s%s" % (VERSION_TUPLE[0], VERSION_TUPLE[1])) HOME_DIR, "gramps%s%s" % (VERSION_TUPLE[0], VERSION_TUPLE[1]))
CUSTOM_FILTERS = os.path.join(VERSION_DIR, "custom_filters.xml") CUSTOM_FILTERS = os.path.join(VERSION_DIR, "custom_filters.xml")
REPORT_OPTIONS = os.path.join(HOME_DIR, "report_options.xml") REPORT_OPTIONS = os.path.join(HOME_DIR, "report_options.xml")
TOOL_OPTIONS = os.path.join(HOME_DIR, "tool_options.xml") TOOL_OPTIONS = os.path.join(HOME_DIR, "tool_options.xml")
ENV_DIR = os.path.join(HOME_DIR, "env") ENV_DIR = os.path.join(HOME_DIR, "env")
TEMP_DIR = os.path.join(HOME_DIR, "temp") TEMP_DIR = os.path.join(HOME_DIR, "temp")
THUMB_DIR = os.path.join(HOME_DIR, "thumb") THUMB_DIR = os.path.join(HOME_DIR, "thumb")
THUMB_NORMAL = os.path.join(THUMB_DIR, "normal") THUMB_NORMAL = os.path.join(THUMB_DIR, "normal")
THUMB_LARGE = os.path.join(THUMB_DIR, "large") THUMB_LARGE = os.path.join(THUMB_DIR, "large")
USER_PLUGINS = os.path.join(VERSION_DIR, "plugins") USER_PLUGINS = os.path.join(VERSION_DIR, "plugins")
# dirs checked/made for each Gramps session # dirs checked/made for each Gramps session
USER_DIRLIST = (USER_HOME, HOME_DIR, VERSION_DIR, ENV_DIR, TEMP_DIR, THUMB_DIR, USER_DIRLIST = (USER_HOME, HOME_DIR, VERSION_DIR, ENV_DIR, TEMP_DIR, THUMB_DIR,
THUMB_NORMAL, THUMB_LARGE, USER_PLUGINS) THUMB_NORMAL, THUMB_LARGE, USER_PLUGINS)
@ -138,15 +142,15 @@ VERSION += git_revision
# #
# Glade files # Glade files
# #
GLADE_DIR = os.path.join(ROOT_DIR, "gui", "glade") GLADE_DIR = os.path.join(ROOT_DIR, "gui", "glade")
GLADE_FILE = os.path.join(GLADE_DIR, "gramps.glade") GLADE_FILE = os.path.join(GLADE_DIR, "gramps.glade")
PERSON_GLADE = os.path.join(GLADE_DIR, "edit_person.glade") PERSON_GLADE = os.path.join(GLADE_DIR, "edit_person.glade")
PLUGINS_GLADE = os.path.join(GLADE_DIR, "plugins.glade") PLUGINS_GLADE = os.path.join(GLADE_DIR, "plugins.glade")
MERGE_GLADE = os.path.join(GLADE_DIR, "mergedata.glade") MERGE_GLADE = os.path.join(GLADE_DIR, "mergedata.glade")
RULE_GLADE = os.path.join(GLADE_DIR, "rule.glade") RULE_GLADE = os.path.join(GLADE_DIR, "rule.glade")
PLUGINS_DIR = os.path.join(ROOT_DIR, "plugins") PLUGINS_DIR = os.path.join(ROOT_DIR, "plugins")
USE_TIPS = False USE_TIPS = False
@ -160,7 +164,6 @@ else:
# Paths to data files. # Paths to data files.
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from gramps.gen.utils.resourcepath import ResourcePath
_resources = ResourcePath() _resources = ResourcePath()
DATA_DIR = _resources.data_dir DATA_DIR = _resources.data_dir
IMAGE_DIR = _resources.image_dir IMAGE_DIR = _resources.image_dir
@ -203,7 +206,6 @@ ENV = {
# Init Localization # Init Localization
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from gramps.gen.utils.grampslocale import GrampsLocale
GRAMPS_LOCALE = GrampsLocale(localedir=_resources.locale_dir) GRAMPS_LOCALE = GrampsLocale(localedir=_resources.locale_dir)
_ = GRAMPS_LOCALE.translation.sgettext _ = GRAMPS_LOCALE.translation.sgettext
GTK_GETTEXT_DOMAIN = 'gtk30' GTK_GETTEXT_DOMAIN = 'gtk30'
@ -213,12 +215,12 @@ GTK_GETTEXT_DOMAIN = 'gtk30'
# About box information # About box information
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
COPYRIGHT_MSG = "© 2001-2006 Donald N. Allingham\n" \ COPYRIGHT_MSG = "© 2001-2006 Donald N. Allingham\n" \
"© 2007-2016 The Gramps Developers" "© 2007-2016 The Gramps Developers"
COMMENTS = _("Gramps\n (Genealogical Research and Analysis " COMMENTS = _("Gramps\n (Genealogical Research and Analysis "
"Management Programming System)\n" "Management Programming System)\n"
"is a personal genealogy program.") "is a personal genealogy program.")
AUTHORS = [ AUTHORS = [
"Alexander Roitman", "Alexander Roitman",
"Benny Malengier", "Benny Malengier",
"Brian Matherly", "Brian Matherly",
@ -233,7 +235,7 @@ AUTHORS = [
AUTHORS_FILE = os.path.join(DATA_DIR, "authors.xml") AUTHORS_FILE = os.path.join(DATA_DIR, "authors.xml")
DOCUMENTERS = [ DOCUMENTERS = [
'Alexander Roitman', 'Alexander Roitman',
] ]
@ -242,12 +244,12 @@ DOCUMENTERS = [
# Constants # Constants
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
THUMBSCALE = 96.0 THUMBSCALE = 96.0
THUMBSCALE_LARGE = 180.0 THUMBSCALE_LARGE = 180.0
XMLFILE = "data.gramps" XMLFILE = "data.gramps"
NO_SURNAME = "(%s)" % _("surname|none") NO_SURNAME = "(%s)" % _("surname|none")
NO_GIVEN = "(%s)" % _("given-name|none") NO_GIVEN = "(%s)" % _("given-name|none")
ARABIC_COMMA = "،" ARABIC_COMMA = "،"
ARABIC_SEMICOLON = "؛" ARABIC_SEMICOLON = "؛"
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
@ -259,18 +261,18 @@ ARABIC_SEMICOLON = "؛"
# Note: Make sure to edit argparser.py _help string too! # Note: Make sure to edit argparser.py _help string too!
# (longName, shortName, type , default, flags, descrip , argDescrip) # (longName, shortName, type , default, flags, descrip , argDescrip)
POPT_TABLE = [ POPT_TABLE = [
("config", 'c', str, None, 0, "Set config setting(s) and start Gramps", ""), ("config", 'c', str, None, 0, "Set config setting(s) and start Gramps", ""),
("open", 'O', str, None, 0, "Open family tree", "FAMILY_TREE"), ("open", 'O', str, None, 0, "Open family tree", "FAMILY_TREE"),
("create", 'C', str, None, 0, "Create or Open family tree", "FAMILY_TREE"), ("create", 'C', str, None, 0, "Create or Open family tree", "FAMILY_TREE"),
("import", 'i', str, None, 0, "Import file", "FILENAME"), ("import", 'i', str, None, 0, "Import file", "FILENAME"),
("export", 'e', str, None, 0, "Export file", "FILENAME"), ("export", 'e', str, None, 0, "Export file", "FILENAME"),
("format", 'f', str, None, 0, 'Specify format', "FORMAT"), ("format", 'f', str, None, 0, 'Specify format', "FORMAT"),
("action", 'a', str, None, 0, 'Specify action', "ACTION"), ("action", 'a', str, None, 0, 'Specify action', "ACTION"),
("options", 'p', str, None, 0, 'Specify options', "OPTIONS_STRING"), ("options", 'p', str, None, 0, 'Specify options', "OPTIONS_STRING"),
("debug", 'd', str, None, 0, 'Enable debug logs', "LOGGER_NAME"), ("debug", 'd', str, None, 0, 'Enable debug logs', "LOGGER_NAME"),
("", 'l', None, None, 0, 'List Family Trees', ""), ("", 'l', None, None, 0, 'List Family Trees', ""),
("", 'L', None, None, 0, 'List Family Tree Details', ""), ("", 'L', None, None, 0, 'List Family Tree Details', ""),
("show", 's', None, None, 0, "Show config settings", ""), ("show", 's', None, None, 0, "Show config settings", ""),
("force-unlock", 'u', None, None, 0, 'Force unlock of family tree', ""), ("force-unlock", 'u', None, None, 0, 'Force unlock of family tree', ""),
("version", 'v', None, None, 0, 'Show versions', ""), ("version", 'v', None, None, 0, 'Show versions', ""),
] ]
@ -321,7 +323,7 @@ LONGOPTS = [
SHORTOPTS = "O:C:i:e:f:a:p:d:c:r:lLthuv?syq" SHORTOPTS = "O:C:i:e:f:a:p:d:c:r:lLthuv?syq"
GRAMPS_UUID = uuid.UUID('516cd010-5a41-470f-99f8-eb22f1098ad6') GRAMPS_UUID = uuid.UUID('516cd010-5a41-470f-99f8-eb22f1098ad6')
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -345,24 +347,24 @@ BACKGROUND_GRAD_AGE = 5
BACKGROUND_SINGLE_COLOR = 6 BACKGROUND_SINGLE_COLOR = 6
BACKGROUND_GRAD_PERIOD = 7 BACKGROUND_GRAD_PERIOD = 7
GENCOLOR = { GENCOLOR = {
BACKGROUND_SCHEME1: ((255, 63, 0), BACKGROUND_SCHEME1: ((255, 63, 0),
(255,175, 15), (255, 175, 15),
(255,223, 87), (255, 223, 87),
(255,255,111), (255, 255, 111),
(159,255,159), (159, 255, 159),
(111,215,255), (111, 215, 255),
( 79,151,255), (79, 151, 255),
(231, 23,255), (231, 23, 255),
(231, 23,121), (231, 23, 121),
(210,170,124), (210, 170, 124),
(189,153,112)), (189, 153, 112)),
BACKGROUND_SCHEME2: ((229,191,252), BACKGROUND_SCHEME2: ((229, 191, 252),
(191,191,252), (191, 191, 252),
(191,222,252), (191, 222, 252),
(183,219,197), (183, 219, 197),
(206,246,209)), (206, 246, 209)),
BACKGROUND_WHITE: ((255,255,255), BACKGROUND_WHITE: ((255, 255, 255),
(255,255,255),), (255, 255, 255),),
} }
MAX_AGE = 100 MAX_AGE = 100

View File

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

View File

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

View File

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

View File

@ -28,15 +28,14 @@
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import time import time
import io
import logging import logging
from xml.parsers.expat import ParserCreate from xml.parsers.expat import ParserCreate, ExpatError
try: try:
import fcntl import fcntl
use_lock = True USE_LOCK = True
except: except ImportError:
use_lock = False USE_LOCK = False
from gramps.gen.const import HOME_DIR, GRAMPS_LOCALE as glocale from gramps.gen.const import HOME_DIR, GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
@ -46,7 +45,7 @@ _ = glocale.translation.gettext
# Constants # Constants
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
GRAMPS_FILENAME = os.path.join(HOME_DIR,"recent-files-gramps.xml") GRAMPS_FILENAME = os.path.join(HOME_DIR, "recent-files-gramps.xml")
MAX_GRAMPS_ITEMS = 10 MAX_GRAMPS_ITEMS = 10
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
@ -59,27 +58,45 @@ class RecentItem(object):
Interface to a single Gramps recent-items item Interface to a single Gramps recent-items item
""" """
def __init__(self,p="", n="",t=0): def __init__(self, p="", n="", t=0):
self.path = p self.path = p
self.name = n self.name = n
self.time = t self.time = t
def set_path(self,val): def set_path(self, val):
"""
Set the file path.
"""
self.path = val self.path = val
def get_path(self): def get_path(self):
"""
Get the file path.
"""
return self.path return self.path
def set_name(self,val): def set_name(self, val):
"""
Set the file name.
"""
self.name = val self.name = val
def get_name(self): def get_name(self):
"""
Get the file name.
"""
return self.name return self.name
def set_time(self,val): def set_time(self, val):
"""
Set the file timestamp.
"""
self.time = int(val) self.time = int(val)
def get_time(self): def get_time(self):
"""
Get the file timestamp.
"""
return self.time return self.time
def __eq__(self, other_item): def __eq__(self, other_item):
@ -100,10 +117,6 @@ class RecentItem(object):
def __ge__(self, other_item): def __ge__(self, other_item):
return self.time >= other_item.time return self.time >= other_item.time
## Python 3, no __cmp__
## def __cmp__(self, other_item):
## return cmp(self.time, other_item.time)
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
# RecentFiles # RecentFiles
@ -118,7 +131,10 @@ class RecentFiles(object):
gramps_parser = RecentParser() gramps_parser = RecentParser()
self.gramps_recent_files = gramps_parser.get() self.gramps_recent_files = gramps_parser.get()
def add(self,item2add): def add(self, item2add):
"""
Add a file to the recent files list.
"""
# First we need to walk the existing items to see # First we need to walk the existing items to see
# if our item is already there # if our item is already there
for item in self.gramps_recent_files: for item in self.gramps_recent_files:
@ -129,11 +145,12 @@ class RecentFiles(object):
return return
# At this point we walked the items and not found one, # At this point we walked the items and not found one,
# so simply inserting a new item in the beginning # so simply inserting a new item in the beginning
self.gramps_recent_files.insert(0,item2add) self.gramps_recent_files.insert(0, item2add)
def rename_filename(self, filename, new_filename):
"""
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 # First we need to walk the existing items to see
# if our item is already there # if our item is already there
found = False found = False
@ -145,7 +162,10 @@ class RecentFiles(object):
if found: if found:
self.gramps_recent_files[index].set_name(new_filename) self.gramps_recent_files[index].set_name(new_filename)
def remove_filename(self,filename): def remove_filename(self, filename):
"""
Remove a file from the recent files list.
"""
# First we need to walk the existing items to see # First we need to walk the existing items to see
# if our item is already there # if our item is already there
found = False found = False
@ -157,8 +177,10 @@ class RecentFiles(object):
if found: if found:
self.gramps_recent_files.pop(index) self.gramps_recent_files.pop(index)
def check_if_recent(self, filename):
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 # First we need to walk the existing items to see
# if our item is already there # if our item is already there
found = False found = False
@ -174,19 +196,21 @@ class RecentFiles(object):
Attempt saving into XML. Attempt saving into XML.
The trick is not to fail under any circumstances. The trick is not to fail under any circumstances.
""" """
fname = os.path.expanduser(GRAMPS_FILENAME)
try: try:
self.do_save() self.do_save(fname)
except: except IOError as err:
pass 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. Saves the current Gramps RecentFiles collection to the associated file.
""" """
with open(os.path.expanduser(GRAMPS_FILENAME), 'w', encoding='utf8') \ with open(fname, 'w', encoding='utf8') as xml_file:
as xml_file: if USE_LOCK:
if use_lock: fcntl.lockf(xml_file, fcntl.LOCK_EX)
fcntl.lockf(xml_file,fcntl.LOCK_EX)
xml_file.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") xml_file.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
xml_file.write('<RecentFiles>\n') xml_file.write('<RecentFiles>\n')
index = 0 index = 0
@ -195,9 +219,12 @@ class RecentFiles(object):
if index > MAX_GRAMPS_ITEMS: if index > MAX_GRAMPS_ITEMS:
break break
xml_file.write(' <RecentItem>\n') xml_file.write(' <RecentItem>\n')
xml_file.write(' <Path><![CDATA[%s]]></Path>\n' % item.get_path()) xml_file.write(' <Path><![CDATA[%s]]></Path>\n' %
xml_file.write(' <Name><![CDATA[%s]]></Name>\n' % item.get_name()) item.get_path())
xml_file.write(' <Timestamp>%d</Timestamp>\n' % item.get_time()) 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(' </RecentItem>\n')
xml_file.write('</RecentFiles>\n') xml_file.write('</RecentFiles>\n')
@ -215,6 +242,8 @@ class RecentParser(object):
def __init__(self): def __init__(self):
self.recent_files = [] self.recent_files = []
self.tlist = []
self.item = None
fname = os.path.expanduser(GRAMPS_FILENAME) fname = os.path.expanduser(GRAMPS_FILENAME)
if not os.path.exists(fname): if not os.path.exists(fname):
@ -222,37 +251,45 @@ class RecentParser(object):
try: try:
with open(fname, "rb") as xml_file: with open(fname, "rb") as xml_file:
if use_lock: if USE_LOCK:
fcntl.lockf(xml_file,fcntl.LOCK_SH) fcntl.lockf(xml_file, fcntl.LOCK_SH)
p = ParserCreate() parser = ParserCreate()
p.StartElementHandler = self.startElement parser.StartElementHandler = self.start_element
p.EndElementHandler = self.endElement parser.EndElementHandler = self.end_element
p.CharacterDataHandler = self.characters parser.CharacterDataHandler = self.characters
p.ParseFile(xml_file) parser.ParseFile(xml_file)
# all advisory locks on a file are released on close # all advisory locks on a file are released on close
except IOError as err: except IOError as err:
logging.warning( logging.warning(
_("Unable to open list of recent DBs file {fname}: {error}" _("Unable to open list of recent DBs file {fname}: {error}"
).format(fname=fname, error=err)) ).format(fname=fname, error=err))
except Exception as err: except ExpatError as err:
logging.error( logging.error(
_("Error parsing list of recent DBs from file {fname}: {error}.\n" _("Error parsing list of recent DBs from file {fname}: "
"This might indicate a damage to your files.\n" "{error}.\nThis might indicate a damage to your files.\n"
"If you're sure there is no problem with other files, " "If you're sure there is no problem with other files, "
"delete it, and restart Gramps." "delete it, and restart Gramps."
).format(fname=fname, error=err)) ).format(fname=fname, error=err))
def get(self): def get(self):
"""
Return a list of recent files.
"""
return self.recent_files return self.recent_files
def startElement(self,tag,attrs): def start_element(self, tag, attrs):
"""
Handler for XML start element.
"""
self.tlist = [] self.tlist = []
if tag == "RecentItem": if tag == "RecentItem":
self.item = RecentItem() self.item = RecentItem()
def endElement(self,tag): def end_element(self, tag):
"""
Handler for XML end element.
"""
text = ''.join(self.tlist) text = ''.join(self.tlist)
if tag == "RecentItem": if tag == "RecentItem":
@ -266,6 +303,9 @@ class RecentParser(object):
self.item.set_time(int(text)) self.item.set_time(int(text))
def characters(self, data): def characters(self, data):
"""
Handler for XML character data.
"""
self.tlist.append(data) self.tlist.append(data)
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
@ -275,9 +315,8 @@ class RecentParser(object):
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
def recent_files(filename, name): 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()) the_time = int(time.time())
gramps_rf = RecentFiles() gramps_rf = RecentFiles()
gramps_item = RecentItem( gramps_item = RecentItem(
@ -288,16 +327,24 @@ def recent_files(filename, name):
gramps_rf.save() gramps_rf.save()
def remove_filename(filename): def remove_filename(filename):
"""
Remove an entry from the Gramps recent items list.
"""
gramps_rf = RecentFiles() gramps_rf = RecentFiles()
gramps_rf.remove_filename(filename) gramps_rf.remove_filename(filename)
gramps_rf.save() gramps_rf.save()
def rename_filename(filename, new_filename): def rename_filename(filename, new_filename):
"""
Rename an entry in the Gramps recent items list.
"""
gramps_rf = RecentFiles() gramps_rf = RecentFiles()
gramps_rf.rename_filename(filename, new_filename) gramps_rf.rename_filename(filename, new_filename)
gramps_rf.save() gramps_rf.save()
def check_if_recent(filename): def check_if_recent(filename):
"""
Check if an entry is present in Gramps recent items list.
"""
gramps_rf = RecentFiles() gramps_rf = RecentFiles()
return gramps_rf.check_if_recent(filename) 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) return glocale.sort_key(name1)
## def by_birthdate(self, first_id, second_id): ## def by_birthdate(self, first_id, second_id):
## """Sort routine for comparing two people by birth dates. If the birth dates ## """Sort routine for comparing two people by birth dates. If the birth
## are equal, sorts by name""" ## dates are equal, sorts by name"""
## first = self.database.get_person_from_handle(first_id) ## first = self.database.get_person_from_handle(first_id)
## second = self.database.get_person_from_handle(second_id) ## second = self.database.get_person_from_handle(second_id)
## ##
@ -218,7 +218,8 @@ class Sort(object):
## return 0 ## return 0
## evt_a = self.database.get_event_from_handle(a_id) ## evt_a = self.database.get_event_from_handle(a_id)
## evt_b = self.database.get_event_from_handle(b_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): def by_event_description_key(self, a_id):
"""Sort routine for comparing two events by their descriptions. """ """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. """ """Sort routine for comparing two media objects by their title. """
if not a_id: if not a_id:
return False return False
a = self.database.get_object_from_handle(a_id) obj_a = self.database.get_object_from_handle(a_id)
return glocale.sort_key(a.desc) return glocale.sort_key(obj_a.desc)

View File

@ -35,8 +35,8 @@ import unicodedata
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
IGNORE = "HW~!@#$%^&*()_+=-`[]\|;:'/?.,<>\" \t\f\v" IGNORE = "HW~!@#$%^&*()_+=-`[]\|;:'/?.,<>\" \t\f\v"
TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ', TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ',
b'012301202245501262301202') b'012301202245501262301202')
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -46,8 +46,8 @@ TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ',
def soundex(strval): def soundex(strval):
"Return the soundex value to a string argument." "Return the soundex value to a string argument."
strval = unicodedata.normalize('NFKD', strval = unicodedata.normalize(
str(strval.upper().strip())).encode('ASCII', 'ignore') 'NFKD', str(strval.upper().strip())).encode('ASCII', 'ignore')
if not strval: if not strval:
return "Z000" return "Z000"
strval = strval.decode('ASCII', 'ignore') strval = strval.decode('ASCII', 'ignore')

View File

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

View File

@ -35,6 +35,7 @@ import time
import collections import collections
import logging import logging
_LOG = logging.getLogger(".gen") _LOG = logging.getLogger(".gen")
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
# Callback updater # Callback updater
@ -53,38 +54,54 @@ class UpdateCallback(object):
:param interval: number of seconds at most between the updates :param interval: number of seconds at most between the updates
:type interval: int :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.update = self.update_real
self.callback = callback self.callback = callback
self.interval = interval self.interval = interval
self.reset()
else: else:
self.update = self.update_empty self.update = self.update_empty
self.count = 0
self.oldval = 0
self.oldtime = 0
self.text = "" self.text = ""
self.total = 1
def reset(self, text=""): def reset(self, text=""):
"""
Reset the count to zero.
"""
self.count = 0 self.count = 0
self.oldval = 0 self.oldval = 0
self.oldtime = 0 self.oldtime = 0
self.text = text self.text = text
def set_total(self, total): def set_total(self, total):
"""
Set the total.
"""
self.total = total self.total = total
if self.total == 0: if self.total == 0:
_LOG.warning('UpdateCallback with total == 0 created') _LOG.warning('UpdateCallback with total == 0 created')
self.total = 1 self.total = 1
def update_empty(self, count=None): def update_empty(self, count=None):
"""
Dummy update used when no callback is specified.
"""
pass pass
def update_real(self, count=None): def update_real(self, count=None):
"""
Called when the count is updated.
"""
self.count += 1 self.count += 1
if not count: if not count:
count = self.count count = self.count
newval = int(100 * count/self.total) newval = int(100 * count/self.total)
newtime = time.time() newtime = time.time()
time_has_come = self.interval and (newtime-self.oldtime>self.interval) time_has_come = self.interval and (newtime-self.oldtime > self.interval)
value_changed = newval!=self.oldval value_changed = newval != self.oldval
if value_changed or time_has_come: if value_changed or time_has_come:
if self.text: if self.text:
self.callback(newval, text=self.text) self.callback(newval, text=self.text)

View File

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