Remove trailing whitespace

This commit is contained in:
Nick Hall
2015-08-23 18:42:07 +01:00
parent 59b0a9ff43
commit cdee00aca2
760 changed files with 16855 additions and 16855 deletions

View File

@@ -21,4 +21,4 @@
Package init for the cli package.
"""
# DO NOT IMPORT METHODS/CLASSES FROM src/gui HERE ! Only __all__
# DO NOT IMPORT METHODS/CLASSES FROM src/gui HERE ! Only __all__

View File

@@ -62,7 +62,7 @@ from gramps.gen.config import config
def _split_options(options_str):
"""
Split the options for the action.
Rules:
* Entries in the list of options are separated by commas without
@@ -74,7 +74,7 @@ def _split_options(options_str):
* Text containing double quotes must be contained in single quotes
* Text containing single quotes must be contained in double quotes
* Text cannot include both single and double quotes
Examples:
Multiple options specified::
@@ -97,9 +97,9 @@ def _split_options(options_str):
in_list = False
quote_type = ""
options_str_dict = {}
for char in options_str:
if not parsing_value:
if not parsing_value:
# Parsing the name of the option
if char == "=":
#print char, "This value ends the name"
@@ -150,11 +150,11 @@ def _split_options(options_str):
class ArgHandler(object):
"""
This class is responsible for the non GUI handling of commands.
The handler is passed a parser object, sanitizes it, and can execute the
The handler is passed a parser object, sanitizes it, and can execute the
actions requested working on a :class:`.DbState`.
"""
def __init__(self, dbstate, parser, sessionmanager,
def __init__(self, dbstate, parser, sessionmanager,
errorfunc=None, gui=False):
self.dbstate = dbstate
self.sm = sessionmanager
@@ -181,7 +181,7 @@ class ArgHandler(object):
self.open = self.__handle_open_option(parser.open, parser.create)
self.sanitize_args(parser.imports, parser.exports)
def __error(self, msg1, msg2=None):
"""
Output an error. Uses errorfunc if given, otherwise a simple print.
@@ -249,10 +249,10 @@ class ArgHandler(object):
if fname != '-' and not os.path.exists(fullpath):
self.__error(_('Error: Import file %s not found.') % fname)
sys.exit(0)
if family_tree_format is None:
# Guess the file format based on the file extension.
# This will get the lower case extension without a period,
# This will get the lower case extension without a period,
# or an empty string.
family_tree_format = os.path.splitext(fname)[-1][1:].lower()
@@ -261,16 +261,16 @@ class ArgHandler(object):
for plugin in pmgr.get_import_plugins():
if family_tree_format == plugin.get_extension():
plugin_found = True
if plugin_found:
self.imports.append((fname, family_tree_format))
else:
self.__error(_('Error: Unrecognized type: "%(format)s" for '
'import file: %(filename)s') %
{'format' : family_tree_format,
'import file: %(filename)s') %
{'format' : family_tree_format,
'filename' : fname})
sys.exit(0)
def __handle_export_option(self, value, family_tree_format):
"""
Handle the "-e" or "--export" option.
@@ -290,17 +290,17 @@ class ArgHandler(object):
message = _("WARNING: Output file already exists!\n"
"WARNING: It will be overwritten:\n %s"
) % fullpath
accepted = self.user.prompt(_('OK to overwrite?'), message,
accepted = self.user.prompt(_('OK to overwrite?'), message,
_('yes'), _('no'))
if accepted:
self.__error(_("Will overwrite the existing file: %s")
self.__error(_("Will overwrite the existing file: %s")
% fullpath)
else:
sys.exit(0)
if family_tree_format is None:
# Guess the file format based on the file extension.
# This will get the lower case extension without a period,
# This will get the lower case extension without a period,
# or an empty string.
family_tree_format = os.path.splitext(fname)[-1][1:].lower()
@@ -309,18 +309,18 @@ class ArgHandler(object):
for plugin in pmgr.get_export_plugins():
if family_tree_format == plugin.get_extension():
plugin_found = True
if plugin_found:
self.exports.append((fullpath, family_tree_format))
else:
self.__error(_("ERROR: Unrecognized format for export file %s")
self.__error(_("ERROR: Unrecognized format for export file %s")
% fname)
sys.exit(0)
def __deduce_db_path(self, db_name_or_path):
"""
Attempt to find a database path for the given parameter.
:returns: The path to a Gramps DB or None if a database can not be
deduced.
"""
@@ -336,20 +336,20 @@ class ArgHandler(object):
name_file_path = os.path.join(fullpath, NAME_FILE)
if os.path.isfile(name_file_path):
db_path = fullpath
return db_path
#-------------------------------------------------------------------------
# Overall argument handler:
# Overall argument handler:
# sorts out the sequence and details of operations
#-------------------------------------------------------------------------
def handle_args_gui(self):
"""
Method to handle the arguments that can be given for a GUI session.
:returns: the filename of the family tree that should be opened if
:returns: the filename of the family tree that should be opened if
user just passed a famtree or a filename.
1. no options: a family tree can be given, if so, this name is tested
and returned. If a filename, it is imported in a new db and name of
new db returned
@@ -380,22 +380,22 @@ class ArgHandler(object):
else:
sys.exit(0)
return db_path
# if not open_gui, parse any command line args. We can only have one
# if not open_gui, parse any command line args. We can only have one
# open argument, and perhaps some import arguments
self.__open_action()
self.__import_action()
return None
def handle_args_cli(self, cleanup=True):
"""
Depending on the given arguments, import or open data, launch
session, write files, and/or perform actions.
:param: climan: the manager of a CLI session
:type: :class:`.CLIManager` object
"""
# Handle the "-l" List Family Trees option.
# Handle the "-l" List Family Trees option.
if self.list:
print(_('List of known Family Trees in your database path\n'))
@@ -406,7 +406,7 @@ class ArgHandler(object):
% {'full_DB_path' : dirname, 'f_t_name' : name})
sys.exit(0)
# Handle the "-L" List Family Trees in detail option.
# Handle the "-L" List Family Trees in detail option.
if self.list_more:
print(_('Gramps Family Trees:'))
summary_list = self.dbman.family_tree_summary()
@@ -420,8 +420,8 @@ class ArgHandler(object):
'item' : item,
'summary' : summary[item] } )
sys.exit(0)
# Handle the "-t" List Family Trees, tab delimited option.
# Handle the "-t" List Family Trees, tab delimited option.
if self.list_table:
print(_('Gramps Family Trees:'))
summary_list = self.dbman.family_tree_summary()
@@ -446,7 +446,7 @@ class ArgHandler(object):
self.__open_action()
self.__import_action()
for (action, op_string) in self.actions:
print(_("Performing action: %s.") % action, file=sys.stderr)
if op_string:
@@ -475,7 +475,7 @@ class ArgHandler(object):
def __import_action(self):
"""
Take action for all given import files.
.. note:: Family trees are not supported.
If a family tree is open, the import happens on top of it. If not
@@ -496,7 +496,7 @@ class ArgHandler(object):
dbid = config.get('behavior.database-backend')
newdb = self.dbstate.make_database(dbid)
newdb.write_version(self.imp_db_path)
try:
self.sm.open_activate(self.imp_db_path)
msg = _("Created empty Family Tree successfully")
@@ -514,11 +514,11 @@ class ArgHandler(object):
def __open_action(self):
"""
Take action on a family tree dir to open. It will be opened in the
Take action on a family tree dir to open. It will be opened in the
session manager
"""
if self.open:
# Family Tree to open was given. Open it
# Family Tree to open was given. Open it
# Then go on and process the rest of the command line arguments.
self.cl = bool(self.exports or self.actions)
@@ -570,7 +570,7 @@ class ArgHandler(object):
#-------------------------------------------------------------------------
def cl_export(self, filename, family_tree_format):
"""
Command-line export routine.
Command-line export routine.
Try to write into filename using the family_tree_format.
"""
pmgr = BasePluginManager.get_instance()
@@ -605,15 +605,15 @@ class ArgHandler(object):
mod = pmgr.load_plugin(pdata)
if not mod:
#import of plugin failed
return
return
category = pdata.category
report_class = eval('mod.' + pdata.reportclass)
options_class = eval('mod.' + pdata.optionclass)
if category in (CATEGORY_BOOK, CATEGORY_CODE):
options_class(self.dbstate.db, name, category,
options_class(self.dbstate.db, name, category,
options_str_dict)
else:
cl_report(self.dbstate.db, name, category,
cl_report(self.dbstate.db, name, category,
report_class, options_class,
options_str_dict)
return
@@ -653,16 +653,16 @@ class ArgHandler(object):
mod = pmgr.load_plugin(pdata)
if not mod:
#import of plugin failed
return
return
category = pdata.category
tool_class = eval('mod.' + pdata.toolclass)
options_class = eval('mod.' + pdata.optionclass)
tool.cli_tool(
dbstate=self.dbstate,
name=name,
category=category,
dbstate=self.dbstate,
name=name,
category=category,
tool_class=tool_class,
options_class=options_class,
options_class=options_class,
options_str_dict=options_str_dict,
user=self.user)
return
@@ -696,7 +696,7 @@ class ArgHandler(object):
book_list = BookList('books.xml', self.dbstate.db)
if name:
if name in book_list.get_book_names():
cl_book(self.dbstate.db, name, book_list.get_book(name),
cl_book(self.dbstate.db, name, book_list.get_book(name),
options_str_dict)
return
msg = _("Unknown book name.")

View File

@@ -83,10 +83,10 @@ Example of usage of Gramps command line interface
1. To import four databases (whose formats can be determined from their names)
and then check the resulting database for errors, one may type:
gramps -i file1.ged -i file2.gpkg -i ~/db3.gramps -i file4.wft -a tool -p name=check.
gramps -i file1.ged -i file2.gpkg -i ~/db3.gramps -i file4.wft -a tool -p name=check.
2. To explicitly specify the formats in the above example, append filenames with appropriate -f options:
gramps -i file1.ged -f gedcom -i file2.gpkg -f gramps-pkg -i ~/db3.gramps -f gramps-xml -i file4.wft -f wft -a tool -p name=check.
gramps -i file1.ged -f gedcom -i file2.gpkg -f gramps-pkg -i ~/db3.gramps -f gramps-xml -i file4.wft -f wft -a tool -p name=check.
3. To record the database resulting from all imports, supply -e flag
(use -f if the filename does not allow Gramps to guess the format):
@@ -154,32 +154,32 @@ class ArgParser(object):
-h, --help Display the help
--usage Display usage information
If the filename (no options) is specified, the interactive session is
launched using data from filename. In this mode (filename, no options), the
If the filename (no options) is specified, the interactive session is
launched using data from filename. In this mode (filename, no options), the
rest of the arguments are ignored. This is a mode suitable by default for
GUI launchers, mime type handlers, and the like.
If no filename or -i option is given, a new interactive session (empty
database) is launched, since no data is given anyway.
If -O or -i option is given, but no -e or -a options are given, an
interactive session is launched with the ``FILENAME`` (specified with -i).
interactive session is launched with the ``FILENAME`` (specified with -i).
If both input (-O or -i) and processing (-e or -a) options are given,
interactive session will not be launched.
When using import ot export options (-i or -e), the -f option may be
specified to indicate the family tree format.
Possible values for ``ACTION`` are: 'report', 'book' and 'tool'.
Configuration ``SETTINGS`` may be specified using the -c option. The
settings are of the form config.setting[:value]. If used without a value,
the setting is shown.
If the -y option is given, the user's acceptance of any CLI prompt is
the setting is shown.
If the -y option is given, the user's acceptance of any CLI prompt is
assumed. (see :meth:`.cli.user.User.prompt`)
If the -q option is given, extra noise on sys.stderr, such as progress
indicators, is suppressed.
"""
@@ -240,9 +240,9 @@ class ArgParser(object):
cliargs += "]"
# Must first do str() of the msg object.
msg = str(msg)
self.errors += [(_('Error parsing the arguments'),
self.errors += [(_('Error parsing the arguments'),
msg + '\n' +
_("Error parsing the arguments: %s \n"
_("Error parsing the arguments: %s \n"
"Type gramps --help for an overview of commands, or "
"read the manual pages.") % cliargs)]
return
@@ -273,13 +273,13 @@ class ArgParser(object):
elif option in ['-i', '--import']:
family_tree_format = None
if opt_ix < len(options) - 1 \
and options[opt_ix + 1][0] in ( '-f', '--format'):
and options[opt_ix + 1][0] in ( '-f', '--format'):
family_tree_format = options[opt_ix + 1][1]
self.imports.append((value, family_tree_format))
elif option in ['-e', '--export']:
family_tree_format = None
if opt_ix < len(options) - 1 \
and options[opt_ix + 1][0] in ( '-f', '--format'):
and options[opt_ix + 1][0] in ( '-f', '--format'):
family_tree_format = options[opt_ix + 1][1]
self.exports.append((value, family_tree_format))
elif option in ['-a', '--action']:
@@ -290,7 +290,7 @@ class ArgParser(object):
continue
options_str = ""
if opt_ix < len(options)-1 \
and options[opt_ix+1][0] in ( '-p', '--options' ):
and options[opt_ix+1][0] in ( '-p', '--options' ):
options_str = options[opt_ix+1][1]
self.actions.append((action, options_str))
elif option in ['-d', '--debug']:
@@ -362,12 +362,12 @@ class ArgParser(object):
self.auto_accept = True
elif option in ['-q', '--quiet']:
self.quiet = True
#clean options list
cleandbg.reverse()
for ind in cleandbg:
del options[ind]
if len(options) > 0 and self.open is None and self.imports == [] \
and not (self.list or self.list_more or self.list_table or
self.help or self.runqml):
@@ -394,10 +394,10 @@ class ArgParser(object):
"""
Determine whether we need a GUI session for the given tasks.
"""
if self.errors:
if self.errors:
#errors in argument parsing ==> give cli error, no gui needed
return False
if self.list or self.list_more or self.list_table or self.help:
return False
@@ -419,10 +419,10 @@ class ArgParser(object):
else:
# data given, but no action/export => GUI
return True
# No data, can only do GUI here
return True
def print_help(self):
"""
If the user gives the --help or -h option, print the output to terminal.

View File

@@ -98,29 +98,29 @@ class CLIDbManager(object):
IND_TVAL = 4
IND_USE_ICON_BOOL = 5
IND_STOCK_ID =6
ICON_NONE = 0
ICON_RECOVERY = 1
ICON_LOCK = 2
ICON_OPEN = 3
ICON_MAP = {
ICON_NONE : None,
ICON_RECOVERY : None,
ICON_LOCK : None,
ICON_OPEN : None,
}
ERROR = _errordialog
def __init__(self, dbstate):
self.dbstate = dbstate
self.msg = None
if dbstate:
self.active = dbstate.db.get_save_path()
else:
self.active = None
self.current_names = []
if dbstate:
self._populate_cli()
@@ -180,7 +180,7 @@ class CLIDbManager(object):
# make the default directory if it does not exist
summary_list = []
for item in self.current_names:
(name, dirpath, path_name, last,
(name, dirpath, path_name, last,
tval, enable, stock_id) = item
retval = self.get_dbdir_summary(dirpath, name)
summary_list.append( retval )
@@ -205,7 +205,7 @@ class CLIDbManager(object):
file.close()
(tval, last) = time_val(dirpath)
(enable, stock_id) = self.icon_values(dirpath, self.active,
(enable, stock_id) = self.icon_values(dirpath, self.active,
self.dbstate.db.is_open())
if (stock_id == 'gramps-lock'):
@@ -271,7 +271,7 @@ class CLIDbManager(object):
newdb.write_version(new_path)
(tval, last) = time_val(new_path)
self.current_names.append((title, new_path, path_name,
last, tval, False, ""))
return new_path, title
@@ -285,7 +285,7 @@ class CLIDbManager(object):
def import_new_db(self, filename, user):
"""
Attempt to import the provided file into a new database.
A new database will only be created if an appropriate importer was
A new database will only be created if an appropriate importer was
found.
:param filename: a fully-qualified path, filename, and
@@ -293,7 +293,7 @@ class CLIDbManager(object):
:param user: a :class:`.cli.user.User` or :class:`.gui.user.User`
instance for managing user interaction.
:returns: A tuple of (new_path, name) for the new database
or (None, None) if no import was performed.
"""
@@ -330,21 +330,21 @@ class CLIDbManager(object):
if format == plugin.get_extension():
new_path, name = self._create_new_db(name)
# Create a new database
self.__start_cursor(_("Importing data..."))
dbid = config.get('behavior.database-backend')
dbase = self.dbstate.make_database(dbid)
dbase.load(new_path, user.callback)
import_function = plugin.get_import_function()
import_function(dbase, filename, user)
# finish up
self.__end_cursor()
dbase.close()
return new_path, name
return None, None
@@ -390,7 +390,7 @@ class CLIDbManager(object):
"""
if os.path.exists(os.path.join(dbpath, "lock")):
os.unlink(os.path.join(dbpath, "lock"))
def icon_values(self, dirpath, active, is_open):
"""
If the directory path is the active path, then return values
@@ -448,7 +448,7 @@ def find_next_db_dir():
def time_val(dirpath):
"""
Return the last modified time of the database. We do this by looking
at the modification time of the meta db file. If this file does not
at the modification time of the meta db file. If this file does not
exist, we indicate that database as never modified.
"""
meta = os.path.join(dirpath, META_NAME)

View File

@@ -9,7 +9,7 @@
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
@@ -50,9 +50,9 @@ from gramps.gen.const import PLUGINS_DIR, USER_PLUGINS
from gramps.gen.db.dbconst import DBBACKEND
from gramps.gen.errors import DbError
from gramps.gen.dbstate import DbState
from gramps.gen.db.exceptions import (DbUpgradeRequiredError,
BsddbDowngradeError,
DbVersionError,
from gramps.gen.db.exceptions import (DbUpgradeRequiredError,
BsddbDowngradeError,
DbVersionError,
DbEnvironmentError,
BsddbUpgradeRequiredError,
BsddbDowngradeRequiredError,
@@ -74,13 +74,13 @@ class CLIDbLoader(object):
"""
def __init__(self, dbstate):
self.dbstate = dbstate
def _warn(self, title, warnmessage):
"""
Issue a warning message. Inherit for GUI action
"""
print(_('WARNING: %s') % warnmessage, file=sys.stderr)
def _errordialog(self, title, errormessage):
"""
Show the error. A title for the error and an errormessage
@@ -88,30 +88,30 @@ class CLIDbLoader(object):
"""
print(_('ERROR: %s') % errormessage, file=sys.stderr)
sys.exit(1)
def _dberrordialog(self, msg):
"""
Show a database error.
Show a database error.
:param msg: an error message
:type msg : string
.. note:: Inherit for GUI action
"""
self._errordialog( '', _("Low level database corruption detected")
self._errordialog( '', _("Low level database corruption detected")
+ '\n' +
_("Gramps has detected a problem in the underlying "
"Berkeley database. This can be repaired from "
"the Family Tree Manager. Select the database and "
'click on the Repair button') + '\n\n' + str(msg))
def _begin_progress(self):
"""
Convenience method to allow to show a progress bar if wanted on load
actions. Inherit if needed
"""
pass
def _pulse_progress(self, value):
"""
Convenience method to allow to show a progress bar if wanted on load
@@ -129,9 +129,9 @@ class CLIDbLoader(object):
def read_file(self, filename):
"""
This method takes care of changing database, and loading the data.
In 3.0 we only allow reading of real databases of filetype
In 3.0 we only allow reading of real databases of filetype
'x-directory/normal'
This method should only return on success.
Returning on failure makes no sense, because we cannot recover,
since database has already been changed.
@@ -144,7 +144,7 @@ class CLIDbLoader(object):
if os.path.exists(filename):
if not os.access(filename, os.W_OK):
mode = "r"
self._warn(_('Read only database'),
self._warn(_('Read only database'),
_('You do not have write access '
'to the selected file.'))
else:
@@ -160,12 +160,12 @@ class CLIDbLoader(object):
dbid = "bsddb"
db = self.dbstate.make_database(dbid)
self.dbstate.change_database(db)
self.dbstate.db.disable_signals()
self._begin_progress()
try:
self.dbstate.db.load(filename, self._pulse_progress, mode)
self.dbstate.db.set_save_path(filename)
@@ -213,8 +213,8 @@ class CLIDbLoader(object):
class CLIManager(object):
"""
Sessionmanager for Gramps. This is in effect a reduced :class:`.ViewManager`
instance (see gui/viewmanager), suitable for CLI actions.
Sessionmanager for Gramps. This is in effect a reduced :class:`.ViewManager`
instance (see gui/viewmanager), suitable for CLI actions.
Aim is to manage a dbstate on which to work (load, unload), and interact
with the plugin session
"""
@@ -233,14 +233,14 @@ class CLIManager(object):
Open and make a family tree active
"""
self._read_recent_file(path)
def _errordialog(self, title, errormessage):
"""
Show the error. A title for the error and an errormessage
"""
print(_('ERROR: %s') % errormessage, file=sys.stderr)
sys.exit(1)
def _read_recent_file(self, filename):
"""
Called when a file needs to be loaded
@@ -250,7 +250,7 @@ class CLIManager(object):
# also updated the recent file menu info in displaystate.py
if not os.path.isdir(filename):
self._errordialog(
_("Could not load a recent Family Tree."),
_("Could not load a recent Family Tree."),
_("Family Tree does not exist, as it has been deleted."))
return
@@ -272,21 +272,21 @@ class CLIManager(object):
title = filename
self._post_load_newdb(filename, 'x-directory/normal', title)
def _post_load_newdb(self, filename, filetype, title=None):
"""
The method called after load of a new database.
The method called after load of a new database.
Here only CLI stuff is done, inherit this method to add extra stuff
"""
self._post_load_newdb_nongui(filename, title)
def _post_load_newdb_nongui(self, filename, title=None):
"""
Called after a new database is loaded.
"""
if not filename:
return
if filename[-1] == os.path.sep:
filename = filename[:-1]
name = os.path.basename(filename)
@@ -298,7 +298,7 @@ class CLIManager(object):
# Window title, recent files, etc related to new file.
self.dbstate.db.set_save_path(filename)
# apply preferred researcher if loaded file has none
res = self.dbstate.db.get_researcher()
owner = get_researcher()
@@ -307,7 +307,7 @@ class CLIManager(object):
# database is empty, then copy default researcher to DB owner
if res.is_empty() and not owner.is_empty() and self.dbstate.db.is_empty():
self.dbstate.db.set_researcher(owner)
name_displayer.set_name_format(self.dbstate.db.name_formats)
fmt_default = config.get('preferences.name-format')
name_displayer.set_default_format(fmt_default)
@@ -319,7 +319,7 @@ class CLIManager(object):
recent_files(filename, name)
self.file_loaded = True
def do_reg_plugins(self, dbstate, uistate):
"""
Register the plugins at initialization time.
@@ -341,15 +341,15 @@ def startcli(errors, argparser):
errmsg = _(' Details: %s') % errors[0][1]
print(errmsg, file=sys.stderr)
sys.exit(1)
if argparser.errors:
if argparser.errors:
errmsg = _('Error encountered in argument parsing: %s') \
% argparser.errors[0][0]
print(errmsg, file=sys.stderr)
errmsg = _(' Details: %s') % argparser.errors[0][1]
print(errmsg, file=sys.stderr)
sys.exit(1)
#we need to keep track of the db state
dbstate = DbState()
@@ -365,7 +365,7 @@ def startcli(errors, argparser):
from .arghandler import ArgHandler
handler = ArgHandler(dbstate, argparser, climanager)
# create a manager to manage the database
handler.handle_args_cli()
sys.exit(0)

View File

@@ -47,14 +47,14 @@ log = logging.getLogger(".")
from gramps.gen.plug import BasePluginManager
from gramps.gen.plug.docgen import (StyleSheet, StyleSheetList, PaperStyle,
PAPER_PORTRAIT, PAPER_LANDSCAPE, graphdoc)
from gramps.gen.plug.menu import (FamilyOption, PersonOption, NoteOption,
MediaOption, PersonListOption, NumberOption,
BooleanOption, DestinationOption, StringOption,
from gramps.gen.plug.menu import (FamilyOption, PersonOption, NoteOption,
MediaOption, PersonListOption, NumberOption,
BooleanOption, DestinationOption, StringOption,
TextOption, EnumeratedListOption, Option)
from gramps.gen.display.name import displayer as name_displayer
from gramps.gen.errors import ReportError, FilterError
from gramps.gen.plug.report import (CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_BOOK,
CATEGORY_GRAPHVIZ, CATEGORY_CODE,
CATEGORY_GRAPHVIZ, CATEGORY_CODE,
ReportOptions, append_styles)
from gramps.gen.plug.report._paper import paper_sizes
from gramps.gen.const import USER_HOME
@@ -75,7 +75,7 @@ def _convert_str_to_match_type(str_val, type_val):
"""
str_val = str_val.strip()
ret_type = type(type_val)
if isinstance(type_val, str):
if ( str_val.startswith("'") and str_val.endswith("'") ) or \
( str_val.startswith('"') and str_val.endswith('"') ):
@@ -83,21 +83,21 @@ def _convert_str_to_match_type(str_val, type_val):
return str(str_val[1:-1])
else:
return str(str_val)
elif ret_type == int:
if str_val.isdigit():
return int(str_val)
else:
print("'%s' is not an integer number" % str_val)
return 0
elif ret_type == float:
try:
return float(str_val)
except ValueError:
print("'%s' is not a decimal number" % str_val)
return 0.0
elif ret_type == bool:
if str_val == str(True):
return True
@@ -106,16 +106,16 @@ def _convert_str_to_match_type(str_val, type_val):
else:
print("'%s' is not a boolean-- try 'True' or 'False'" % str_val)
return False
elif ret_type == list:
ret_val = []
if not ( str_val.startswith("[") and str_val.endswith("]") ):
print("'%s' is not a list-- try: [%s]" % (str_val, str_val))
return ret_val
entry = ""
quote_type = None
# Search through characters between the brackets
for char in str_val[1:-1]:
if (char == "'" or char == '"') and quote_type == None:
@@ -135,21 +135,21 @@ def _convert_str_to_match_type(str_val, type_val):
if entry != "":
# Add the last entry
ret_val.append(entry.strip())
return ret_val
def _validate_options(options, dbase):
"""
Validate all options by making sure that their values are consistent with
the database.
menu: The Menu class
dbase: the database the options will be applied to
"""
if not hasattr(options, "menu"):
return
menu = options.menu
for name in menu.get_all_option_names():
option = menu.get_option_by_name(name)
@@ -169,7 +169,7 @@ def _validate_options(options, dbase):
file=sys.stderr)
if person:
option.set_value(person.get_gramps_id())
elif isinstance(option, FamilyOption):
fid = option.get_value()
family = dbase.get_family_from_gramps_id(fid)
@@ -204,7 +204,7 @@ class CommandLineReport(object):
def __init__(self, database, name, category, option_class, options_str_dict,
noopt=False):
pmgr = BasePluginManager.get_instance()
self.__textdoc_plugins = []
self.__drawdoc_plugins = []
@@ -218,7 +218,7 @@ class CommandLineReport(object):
plugin.get_draw_support() and \
plugin.get_extension():
self.__bookdoc_plugins.append(plugin)
self.database = database
self.category = category
self.format = None
@@ -282,20 +282,20 @@ class CommandLineReport(object):
if noopt:
return
self.options_help['of'][2] = os.path.join(USER_HOME,
self.options_help['of'][2] = os.path.join(USER_HOME,
"whatever_name")
if self.category == CATEGORY_TEXT:
for plugin in self.__textdoc_plugins:
self.options_help['off'][2].append(
self.options_help['off'][2].append(
plugin.get_extension() + "\t" + plugin.get_description() )
elif self.category == CATEGORY_DRAW:
for plugin in self.__drawdoc_plugins:
self.options_help['off'][2].append(
self.options_help['off'][2].append(
plugin.get_extension() + "\t" + plugin.get_description() )
elif self.category == CATEGORY_BOOK:
for plugin in self.__bookdoc_plugins:
self.options_help['off'][2].append(
self.options_help['off'][2].append(
plugin.get_extension() + "\t" + plugin.get_description() )
elif self.category == CATEGORY_GRAPHVIZ:
for graph_format in graphdoc.FORMATS:
@@ -305,7 +305,7 @@ class CommandLineReport(object):
self.options_help['off'][2] = "NA"
self.options_help['papers'][2] = \
[ paper.get_name() for paper in paper_sizes
[ paper.get_name() for paper in paper_sizes
if paper.get_name() != 'Custom Size' ]
self.options_help['papero'][2] = [
@@ -322,9 +322,9 @@ class CommandLineReport(object):
# Read all style sheets available for this item
style_file = self.option_class.handler.get_stylesheet_savefile()
self.style_list = StyleSheetList(style_file, default_style)
self.options_help['style'][2] = self.style_list.get_style_names()
def init_report_options(self):
"""
Initialize the options that are defined by each report.
@@ -344,7 +344,7 @@ class CommandLineReport(object):
for name in menu.get_all_option_names():
option = menu.get_option_by_name(name)
self.options_dict[name] = option.get_value()
def init_report_options_help(self):
"""
Initialize help for the options that are defined by each report.
@@ -356,7 +356,7 @@ class CommandLineReport(object):
for name in menu.get_all_option_names():
option = menu.get_option_by_name(name)
self.options_help[name] = [ "", option.get_help() ]
if isinstance(option, PersonOption):
id_list = []
for person_handle in self.database.get_person_handles(True):
@@ -426,7 +426,7 @@ class CommandLineReport(object):
"and acceptable values")
% {'donottranslate' : "show=option"},
file=sys.stderr)
def parse_options(self):
"""
Load the options that the user has entered.
@@ -440,7 +440,7 @@ class CommandLineReport(object):
_format_str = self.options_str_dict.pop('off', None)
if _format_str:
self.options_dict['off'] = _format_str
self.css_filename = None
_chosen_format = None
@@ -489,7 +489,7 @@ class CommandLineReport(object):
for opt in self.options_str_dict:
if opt in self.options_dict:
self.options_dict[opt] = \
_convert_str_to_match_type(self.options_str_dict[opt],
_convert_str_to_match_type(self.options_str_dict[opt],
self.options_dict[opt])
self.option_class.handler.options_dict[opt] = \
@@ -498,7 +498,7 @@ class CommandLineReport(object):
if menu and opt in menu_opt_names:
option = menu.get_option_by_name(opt)
option.set_value(self.options_dict[opt])
else:
print(_("Ignoring unknown option: %s") % opt, file=sys.stderr)
print(_(" Valid options are:"),
@@ -507,7 +507,7 @@ class CommandLineReport(object):
print(_(" Use '%(donottranslate)s' to see description "
"and acceptable values") %
{'donottranslate' : "show=option"}, file=sys.stderr)
self.option_class.handler.output = self.options_dict['of']
self.paper = paper_sizes[0] # make sure one exists
@@ -517,7 +517,7 @@ class CommandLineReport(object):
self.option_class.handler.set_paper(self.paper)
self.orien = self.options_dict['papero']
self.marginl = self.options_dict['paperml']
self.marginr = self.options_dict['papermr']
self.margint = self.options_dict['papermt']
@@ -609,11 +609,11 @@ class CommandLineReport(object):
# Command-line report generic task
#
#------------------------------------------------------------------------
def cl_report(database, name, category, report_class, options_class,
def cl_report(database, name, category, report_class, options_class,
options_str_dict):
err_msg = _("Failed to write report. ")
clr = CommandLineReport(database, name, category, options_class,
clr = CommandLineReport(database, name, category, options_class,
options_str_dict)
# Exit here if show option was given
@@ -676,7 +676,7 @@ def run_report(db, name, **options_str_dict):
options_str_dict is the same kind of options
given at the command line. For example:
>>> run_report(db, "ancestor_report", off="txt",
of="ancestor-007.txt", pid="I37")
@@ -703,10 +703,10 @@ def run_report(db, name, **options_str_dict):
report_class = getattr(mod, pdata.reportclass)
options_class = getattr(mod, pdata.optionclass)
if category in (CATEGORY_BOOK, CATEGORY_CODE):
options_class(db, name, category,
options_class(db, name, category,
options_str_dict)
else:
clr = cl_report(db, name, category,
clr = cl_report(db, name, category,
report_class, options_class,
options_str_dict)
return clr
@@ -725,7 +725,7 @@ def cl_book(database, name, book, options_str_dict):
# Exit here if show option was given
if clr.show:
return
# write report
doc = clr.format(None,
PaperStyle(clr.paper, clr.orien, clr.marginl,

View File

@@ -9,7 +9,7 @@
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
@@ -32,7 +32,7 @@ try:
from unittest.mock import Mock
MOCKING = True
except:
MOCKING = False
print ("Mocking disabled", sys.exc_info()[0:2])

View File

@@ -67,9 +67,9 @@ class Test(unittest.TestCase):
def test1_setup_works(self):
self.assertTrue(os.path.exists(ddir), "data dir %r exists" % ddir)
self.assertTrue(os.path.exists(min1r), "data file %r exists" % min1r)
self.assertFalse(os.path.exists(out_ged),
self.assertFalse(os.path.exists(out_ged),
"NO out file %r yet" % out_ged)
# This tests the fix for bug #1331-1334
# read trivial gedcom input, write gedcom output
def test2_exec_CLI(self):
@@ -91,7 +91,7 @@ class Test(unittest.TestCase):
g = re.search("INDI", content)
self.assertTrue(g, "found 'INDI' in output file")
# this verifies that files in the temporary "import dir"
# this verifies that files in the temporary "import dir"
# get cleaned before (and after) running a CLI
# (eg cleanout stale files from prior crash-runs)
def test3_files_in_import_dir(self):
@@ -104,7 +104,7 @@ class Test(unittest.TestCase):
for fn in bogofiles:
with io.open(fn, "w") as f:
f.write("garbage")
# ~same as test 2
pyexec = sys.executable
ifile = min1r

View File

@@ -9,7 +9,7 @@
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
@@ -33,7 +33,7 @@ try:
from unittest.mock import Mock, patch
MOCKING = True
except:
MOCKING = False
print ("Mocking disabled", sys.exc_info()[0:2])
@@ -69,7 +69,7 @@ class TestUser_prompt(unittest.TestCase):
self.user._input.assert_called_once_with()
def assert_prompt_contains_text(self, text,
title=TestUser.TITLE, msg=TestUser.MSG,
title=TestUser.TITLE, msg=TestUser.MSG,
accept=TestUser.ACCEPT, reject=TestUser.REJECT):
self.user._input.configure_mock(return_value = TestUser.REJECT)
self.user.prompt(title, msg, accept, reject)
@@ -160,7 +160,7 @@ class TestUser_progress(unittest.TestCase):
self.expected_output = list(self.user._fileout.method_calls)
self.user._fileout.reset_mock()
self.assertTrue(
len(self.user._fileout.method_calls) == 0,
len(self.user._fileout.method_calls) == 0,
list(self.user._fileout.method_calls))
with self.user.progress("Foo", "Bar", 0) as step:
@@ -168,7 +168,7 @@ class TestUser_progress(unittest.TestCase):
step()
# Output using `with' differs from one with `progress_...'
self.assertEqual(self.expected_output,
self.assertEqual(self.expected_output,
list(self.user._fileout.method_calls))
def test_ends_progress_upon_exception_in_with(self):

View File

@@ -60,7 +60,7 @@ class User(user.User):
self.current_step = 0;
self._input = input
def yes(*args):
def yes(*args):
return True
if auto_accept:
@@ -68,11 +68,11 @@ class User(user.User):
if quiet:
self.begin_progress = self.end_progress = self.step_progress = \
self._default_callback = yes
def begin_progress(self, title, message, steps):
"""
Start showing a progress indicator to the user.
:param title: the title of the progress meter
:type title: str
:param message: the message associated with the progress meter
@@ -90,7 +90,7 @@ class User(user.User):
self._fileout.write(_SPINNER[self.current_step])
else:
self._fileout.write("00%")
def step_progress(self):
"""
Advance the progress meter.
@@ -108,11 +108,11 @@ class User(user.User):
Stop showing the progress indicator to the user.
"""
self._fileout.write("\r100%\n")
def prompt(self, title, message, accept_label, reject_label, parent=None):
"""
Prompt the user with a message to select an alternative.
:param title: the title of the question, e.g.: "Undo history warning"
:type title: str
:param message: the message, e.g.: "Proceeding with the tool will erase
@@ -140,11 +140,11 @@ class User(user.User):
return reply == "" or reply == accept_label
except EOFError:
return False
def warn(self, title, warning=""):
"""
Warn the user.
:param title: the title of the warning
:type title: str
:param warning: the warning
@@ -152,11 +152,11 @@ class User(user.User):
:returns: none
"""
self._fileout.write("%s %s" % (title, warning))
def notify_error(self, title, error=""):
"""
Notify the user of an error.
:param title: the title of the error
:type title: str
:param error: the error message
@@ -171,7 +171,7 @@ class User(user.User):
def notify_db_error(self, error):
"""
Notify the user of a DB error.
:param error: the error message
:type error: str
:returns: none