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",
"mime", "plug", "proxy", "simple", "utils" ]
__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
#---------------------------------------------------------------
#
@ -134,7 +134,7 @@ register('behavior.check-for-update-types', ["new"])
register('behavior.last-check-for-updates', "1970/01/01")
register('behavior.previously-seen-updates', [])
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.date-about-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.addons-url', "https://raw.githubusercontent.com/gramps-project/addons/master/gramps50")
register('export.proxy-order', [
["privacy", 0],
["living", 0],
["person", 0],
["note", 0],
["reference", 0],
])
register('export.proxy-order',
[["privacy", 0],
["living", 0],
["person", 0],
["note", 0],
["reference", 0]]
)
register('geography.center-lon', 0.0)
register('geography.lock', False)
@ -365,7 +365,7 @@ if not os.path.exists(CONFIGMAN.filename):
# read it in old style:
logging.warning("Importing old key file 'keys.ini'...")
CONFIGMAN.load(os.path.join(HOME_DIR, "keys.ini"),
oldstyle=True)
oldstyle=True)
logging.warning("Done importing old key file 'keys.ini'")
# other version upgrades here...
# check previous version of gramps:
@ -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,23 +41,27 @@ import uuid
#-------------------------------------------------------------------------
from .git_revision import get_git_revision
from .constfunc import get_env_var
#-------------------------------------------------------------------------
#
# Gramps Version
#
#-------------------------------------------------------------------------
PROGRAM_NAME = "Gramps"
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_BUGHOME = "http://bugs.gramps-project.org"
URL_BUGTRACKER = "http://bugs.gramps-project.org/bug_report_page.php"
URL_WIKISTRING = "http://gramps-project.org/wiki/index.php?title="
URL_BUGHOME = "http://bugs.gramps-project.org"
URL_BUGTRACKER = "http://bugs.gramps-project.org/bug_report_page.php"
URL_WIKISTRING = "http://gramps-project.org/wiki/index.php?title="
URL_MANUAL_PAGE = "Gramps_%s_Wiki_Manual" % major_version
URL_MANUAL_DATA = '%s_-_Entering_and_editing_data:_detailed' % URL_MANUAL_PAGE
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
WIKI_FAQ = "FAQ"
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
#-------------------------------------------------------------------------
@ -73,13 +77,13 @@ WIKI_EXTRAPLUGINS_RAWDATA = "Plugins%s&action=raw" % major_version
# Mime Types
#
#-------------------------------------------------------------------------
APP_FAMTREE = 'x-directory/normal'
APP_GRAMPS = "application/x-gramps"
APP_GRAMPS_XML = "application/x-gramps-xml"
APP_GEDCOM = "application/x-gedcom"
APP_GRAMPS_PKG = "application/x-gramps-package"
APP_GENEWEB = "application/x-geneweb"
APP_VCARD = ["text/x-vcard", "text/x-vcalendar"]
APP_FAMTREE = 'x-directory/normal'
APP_GRAMPS = "application/x-gramps"
APP_GRAMPS_XML = "application/x-gramps-xml"
APP_GEDCOM = "application/x-gedcom"
APP_GRAMPS_PKG = "application/x-gramps-package"
APP_GENEWEB = "application/x-geneweb"
APP_VCARD = ["text/x-vcard", "text/x-vcalendar"]
#-------------------------------------------------------------------------
#
@ -102,19 +106,19 @@ else:
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]))
CUSTOM_FILTERS = os.path.join(VERSION_DIR, "custom_filters.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")
TEMP_DIR = os.path.join(HOME_DIR, "temp")
THUMB_DIR = os.path.join(HOME_DIR, "thumb")
THUMB_NORMAL = os.path.join(THUMB_DIR, "normal")
THUMB_LARGE = os.path.join(THUMB_DIR, "large")
USER_PLUGINS = os.path.join(VERSION_DIR, "plugins")
ENV_DIR = os.path.join(HOME_DIR, "env")
TEMP_DIR = os.path.join(HOME_DIR, "temp")
THUMB_DIR = os.path.join(HOME_DIR, "thumb")
THUMB_NORMAL = os.path.join(THUMB_DIR, "normal")
THUMB_LARGE = os.path.join(THUMB_DIR, "large")
USER_PLUGINS = os.path.join(VERSION_DIR, "plugins")
# dirs checked/made for each Gramps session
USER_DIRLIST = (USER_HOME, HOME_DIR, VERSION_DIR, ENV_DIR, TEMP_DIR, THUMB_DIR,
THUMB_NORMAL, THUMB_LARGE, USER_PLUGINS)
@ -138,15 +142,15 @@ VERSION += git_revision
#
# Glade files
#
GLADE_DIR = os.path.join(ROOT_DIR, "gui", "glade")
GLADE_FILE = os.path.join(GLADE_DIR, "gramps.glade")
PERSON_GLADE = os.path.join(GLADE_DIR, "edit_person.glade")
PLUGINS_GLADE = os.path.join(GLADE_DIR, "plugins.glade")
MERGE_GLADE = os.path.join(GLADE_DIR, "mergedata.glade")
RULE_GLADE = os.path.join(GLADE_DIR, "rule.glade")
GLADE_DIR = os.path.join(ROOT_DIR, "gui", "glade")
GLADE_FILE = os.path.join(GLADE_DIR, "gramps.glade")
PERSON_GLADE = os.path.join(GLADE_DIR, "edit_person.glade")
PLUGINS_GLADE = os.path.join(GLADE_DIR, "plugins.glade")
MERGE_GLADE = os.path.join(GLADE_DIR, "mergedata.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
@ -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'
@ -213,12 +215,12 @@ GTK_GETTEXT_DOMAIN = 'gtk30'
# About box information
#
#-------------------------------------------------------------------------
COPYRIGHT_MSG = "© 2001-2006 Donald N. Allingham\n" \
"© 2007-2016 The Gramps Developers"
COMMENTS = _("Gramps\n (Genealogical Research and Analysis "
"Management Programming System)\n"
"is a personal genealogy program.")
AUTHORS = [
COPYRIGHT_MSG = "© 2001-2006 Donald N. Allingham\n" \
"© 2007-2016 The Gramps Developers"
COMMENTS = _("Gramps\n (Genealogical Research and Analysis "
"Management Programming System)\n"
"is a personal genealogy program.")
AUTHORS = [
"Alexander Roitman",
"Benny Malengier",
"Brian Matherly",
@ -233,7 +235,7 @@ AUTHORS = [
AUTHORS_FILE = os.path.join(DATA_DIR, "authors.xml")
DOCUMENTERS = [
DOCUMENTERS = [
'Alexander Roitman',
]
@ -242,12 +244,12 @@ DOCUMENTERS = [
# Constants
#
#-------------------------------------------------------------------------
THUMBSCALE = 96.0
THUMBSCALE = 96.0
THUMBSCALE_LARGE = 180.0
XMLFILE = "data.gramps"
NO_SURNAME = "(%s)" % _("surname|none")
NO_GIVEN = "(%s)" % _("given-name|none")
ARABIC_COMMA = "،"
XMLFILE = "data.gramps"
NO_SURNAME = "(%s)" % _("surname|none")
NO_GIVEN = "(%s)" % _("given-name|none")
ARABIC_COMMA = "،"
ARABIC_SEMICOLON = "؛"
#-------------------------------------------------------------------------
@ -259,18 +261,18 @@ ARABIC_SEMICOLON = "؛"
# Note: Make sure to edit argparser.py _help string too!
# (longName, shortName, type , default, flags, descrip , argDescrip)
POPT_TABLE = [
("config", 'c', str, None, 0, "Set config setting(s) and start Gramps", ""),
("open", 'O', str, None, 0, "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"),
("export", 'e', str, None, 0, "Export file", "FILENAME"),
("format", 'f', str, None, 0, 'Specify format', "FORMAT"),
("action", 'a', str, None, 0, 'Specify action', "ACTION"),
("options", 'p', str, None, 0, 'Specify options', "OPTIONS_STRING"),
("debug", 'd', str, None, 0, 'Enable debug logs', "LOGGER_NAME"),
("", 'l', None, None, 0, 'List Family Trees', ""),
("", 'L', None, None, 0, 'List Family Tree Details', ""),
("show", 's', None, None, 0, "Show config settings", ""),
("config", 'c', str, None, 0, "Set config setting(s) and start Gramps", ""),
("open", 'O', str, None, 0, "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"),
("export", 'e', str, None, 0, "Export file", "FILENAME"),
("format", 'f', str, None, 0, 'Specify format', "FORMAT"),
("action", 'a', str, None, 0, 'Specify action', "ACTION"),
("options", 'p', str, None, 0, 'Specify options', "OPTIONS_STRING"),
("debug", 'd', str, None, 0, 'Enable debug logs', "LOGGER_NAME"),
("", 'l', None, None, 0, 'List Family Trees', ""),
("", 'L', None, None, 0, 'List Family Tree Details', ""),
("show", 's', None, None, 0, "Show config settings", ""),
("force-unlock", 'u', None, None, 0, 'Force unlock of family tree', ""),
("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"
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_GRAD_PERIOD = 7
GENCOLOR = {
BACKGROUND_SCHEME1: ((255, 63, 0),
(255,175, 15),
(255,223, 87),
(255,255,111),
(159,255,159),
(111,215,255),
( 79,151,255),
(231, 23,255),
(231, 23,121),
(210,170,124),
(189,153,112)),
BACKGROUND_SCHEME2: ((229,191,252),
(191,191,252),
(191,222,252),
(183,219,197),
(206,246,209)),
BACKGROUND_WHITE: ((255,255,255),
(255,255,255),),
BACKGROUND_SCHEME1: ((255, 63, 0),
(255, 175, 15),
(255, 223, 87),
(255, 255, 111),
(159, 255, 159),
(111, 215, 255),
(79, 151, 255),
(231, 23, 255),
(231, 23, 121),
(210, 170, 124),
(189, 153, 112)),
BACKGROUND_SCHEME2: ((229, 191, 252),
(191, 191, 252),
(191, 222, 252),
(183, 219, 197),
(206, 246, 209)),
BACKGROUND_WHITE: ((255, 255, 255),
(255, 255, 255),),
}
MAX_AGE = 100

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):
@ -54,8 +65,8 @@ class DbState(Callback):
just a place holder until a real DB is assigned.
"""
Callback.__init__(self)
self.db = self.make_database("bsddb")
self.open = False
self.db = self.make_database("bsddb")
self.open = False
self.stack = []
def change_database(self, database):
@ -82,7 +93,7 @@ class DbState(Callback):
config.get('preferences.pprefix'),
config.get('preferences.eprefix'),
config.get('preferences.rprefix'),
config.get('preferences.nprefix') )
config.get('preferences.nprefix'))
self.open = True
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.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,23 +19,30 @@
# 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(
"{} \"{}\"".format(command, path),
shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
except:
proc = subprocess.Popen(
"{} \"{}\"".format(command, path),
shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
except OSError:
return "" # subprocess failed
# subprocess worked
if stdout and len(stdout) > 0: # has output
try:
stdout = stdout.decode("utf-8", errors = 'replace')
stdout = stdout.decode("utf-8", errors='replace')
except UnicodeDecodeError:
pass
return "-" + stdout if stdout else ""

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
@ -46,7 +45,7 @@ _ = glocale.translation.gettext
# 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
#-------------------------------------------------------------------------
@ -59,27 +58,45 @@ class RecentItem(object):
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.name = n
self.time = t
def set_path(self,val):
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):
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):
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
@ -118,7 +131,10 @@ class RecentFiles(object):
gramps_parser = RecentParser()
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
# if our item is already there
for item in self.gramps_recent_files:
@ -129,11 +145,12 @@ class RecentFiles(object):
return
# At this point we walked the items and not found one,
# 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
# if our item is already there
found = False
@ -145,7 +162,10 @@ class RecentFiles(object):
if found:
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
# 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):
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,19 +196,21 @@ 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:
fcntl.lockf(xml_file,fcntl.LOCK_EX)
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')
index = 0
@ -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:
fcntl.lockf(xml_file,fcntl.LOCK_SH)
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:
_("Unable to open list of recent DBs file {fname}: {error}"
).format(fname=fname, error=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"
"If you're sure there is no problem with other files, "
"delete it, and restart Gramps."
).format(fname=fname, error=err))
_("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

@ -35,8 +35,8 @@ import unicodedata
#
#-------------------------------------------------------------------------
IGNORE = "HW~!@#$%^&*()_+=-`[]\|;:'/?.,<>\" \t\f\v"
TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ',
b'012301202245501262301202')
TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ',
b'012301202245501262301202')
#-------------------------------------------------------------------------
#
@ -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,38 +54,54 @@ 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
newval = int(100 * count/self.total)
newtime = time.time()
time_has_come = self.interval and (newtime-self.oldtime>self.interval)
value_changed = newval!=self.oldval
time_has_come = self.interval and (newtime-self.oldtime > self.interval)
value_changed = newval != self.oldval
if value_changed or time_has_come:
if 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.
#
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