Пример #1
0
    def __handle_import_option(self, value, family_tree_format):
        """
        Handle the "-i" or "--import" option.
        Only Files supported by a plugin can be imported, so not Family Trees.
        """
        fname = value
        fullpath = os.path.abspath(os.path.expanduser(fname))
        if fname != '-' and not os.path.exists(fullpath):
            self.__error(_('Error: Import file %s not found.') % fname)
            sys.exit(1)

        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,
            # or an empty string.
            family_tree_format = os.path.splitext(fname)[-1][1:].lower()

        pmgr = BasePluginManager.get_instance()
        plugin_found = False
        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,
                               'filename' : fname})
            sys.exit(1)
Пример #2
0
    def __init__(self,
                 database,
                 name,
                 category,
                 option_class,
                 options_str_dict,
                 noopt=False):

        pmgr = BasePluginManager.get_instance()
        self.__textdoc_plugins = []
        self.__drawdoc_plugins = []
        self.__bookdoc_plugins = []
        for plugin in pmgr.get_docgen_plugins():
            if plugin.get_text_support() and plugin.get_extension():
                self.__textdoc_plugins.append(plugin)
            if plugin.get_draw_support() and plugin.get_extension():
                self.__drawdoc_plugins.append(plugin)
            if (plugin.get_extension() and plugin.get_text_support()
                    and plugin.get_draw_support()):
                self.__bookdoc_plugins.append(plugin)

        self.database = database
        self.category = category

        self.options_dict = None  # keep pylint happy
        self.options_help = None
        self.paper = None
        self.orien = None
        self.marginl = None
        self.marginr = None
        self.margint = None
        self.marginb = None
        self.doc_options = None
        self.doc_option_class = None
        self.selected_style = None
        self.style_list = None
        self.css_filename = None
        self.format = None
        self.raw_name = name

        self.option_class = option_class(name, database)
        if category == CATEGORY_GRAPHVIZ:
            # Need to include Graphviz options
            self.__gvoptions = graphdoc.GVOptions()
            menu = self.option_class.menu
            self.__gvoptions.add_menu_options(menu)
            for name in menu.get_all_option_names():
                if name not in self.option_class.options_dict:
                    self.option_class.options_dict[
                        name] = menu.get_option_by_name(name).get_value()
        self.option_class.load_previous_values()
        _validate_options(self.option_class, database)
        self.show = options_str_dict.pop('show', None)

        self.options_str_dict = options_str_dict
        self.init_standard_options(noopt)
        self.init_report_options()
        self.parse_options()
        self.init_report_options_help()
        self.show_options()
Пример #3
0
 def __init__(self, dbstate, setloader, user):
     self.dbstate = dbstate
     if setloader:
         self.db_loader = CLIDbLoader(self.dbstate)
     else:
         self.db_loader = None
     self.file_loaded = False
     self._pmgr = BasePluginManager.get_instance()
     self.user = user
Пример #4
0
 def cl_export(self, filename, family_tree_format):
     """
     Command-line export routine.
     Try to write into filename using the family_tree_format.
     """
     pmgr = BasePluginManager.get_instance()
     for plugin in pmgr.get_export_plugins():
         if family_tree_format == plugin.get_extension():
             export_function = plugin.get_export_function()
             export_function(self.dbstate.db, filename, self.user)
Пример #5
0
    def __handle_export_option(self, value, family_tree_format):
        """
        Handle the "-e" or "--export" option.

        .. note:: this can only happen in the CLI version.
        """
        if self.gui:
            return
        fname = value
        if fname == '-':
            fullpath = '-'
        else:
            fullpath = os.path.abspath(os.path.expanduser(fname))
            if os.path.exists(fullpath):
                message = _(
                    "WARNING: Output file already exists!\n"
                    "WARNING: It will be overwritten:\n   %s") % fullpath
                accepted = self.user.prompt(_('OK to overwrite?'),
                                            message,
                                            _('yes'),
                                            _('no'),
                                            default_label=_('yes'))
                if accepted:
                    self.__error(
                        _("Will overwrite the existing file: %s") % fullpath)
                else:
                    sys.exit(1)

        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,
            # or an empty string.
            family_tree_format = os.path.splitext(fname)[-1][1:].lower()

        pmgr = BasePluginManager.get_instance()
        plugin_found = False
        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") % fname)
            sys.exit(1)
Пример #6
0
def run_report(db, name, username=None, **options_str_dict):
    """
    Given a database, run a given report.

    db is a Db database

    name is the name of a report

    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")

    returns CommandLineReport (clr) if successfully runs the report,
    None otherwise.

    You can see:
       options and values used in  clr.option_class.options_dict
       filename in clr.option_class.get_output()
    """
    dbstate = DbState()
    climanager = CLIManager(dbstate, False, User()) # don't load db
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    cl_list = pmgr.get_reg_reports()
    clr = None
    for pdata in cl_list:
        if name == pdata.id:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                #import of plugin failed
                return clr
            category = pdata.category
            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_str_dict)
            else:
                clr = cl_report(db, name, category,
                                report_class, options_class,
                                options_str_dict, username)
                return clr
    return clr
Пример #7
0
    def cl_action(self, action, options_str, username):
        """
        Command-line action routine. Try to perform specified action.
        """
        pmgr = BasePluginManager.get_instance()
        if action == "report":
            try:
                options_str_dict = _split_options(options_str)
            except:
                options_str_dict = {}
                print(_("Ignoring invalid options string."),
                      file=sys.stderr)

            name = options_str_dict.pop('name', None)
            _cl_list = pmgr.get_reg_reports(gui=False)
            if name:
                for pdata in _cl_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            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_str_dict)
                        else:
                            cl_report(self.dbstate.db, name, category,
                                      report_class, options_class,
                                      options_str_dict, username)
                        return
                # name exists, but is not in the list of valid report names
                msg = _("Unknown report name.")
            else:
                msg = _("Report name not given. "
                        "Please use one of %(donottranslate)s=reportname"
                       ) % {'donottranslate' : '[-p|--options] name'}

            print(_("%s\n Available names are:") % msg, file=sys.stderr)
            for pdata in sorted(_cl_list, key=lambda pdata: pdata.id.lower()):
                # Print cli report name ([item[0]), GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print("   %s%s- %s" % (pdata.id,
                                           " " * (26 - len(pdata.id)),
                                           pdata.name),
                          file=sys.stderr)
                else:
                    print("   %s\t- %s" % (pdata.id, pdata.name),
                          file=sys.stderr)

        elif action == "book":
            try:
                options_str_dict = _split_options(options_str)
            except:
                options_str_dict = {}
                print(_("Ignoring invalid options string."),
                      file=sys.stderr)

            name = options_str_dict.pop('name', None)
            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),
                            options_str_dict, username)
                    return
                msg = _("Unknown book name.")
            else:
                msg = _("Book name not given. "
                        "Please use one of %(donottranslate)s=bookname."
                       ) % {'donottranslate' : '[-p|--options] name'}

            print(_("%s\n Available names are:") % msg, file=sys.stderr)
            for name in sorted(book_list.get_book_names()):
                print("   %s" % name, file=sys.stderr)

        else:
            print(_("Unknown action: %s.") % action, file=sys.stderr)
            sys.exit(1)
Пример #8
0
    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
        found.

        :param filename: a fully-qualified path, filename, and
                         extension to open.

        :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.
        """
        pmgr = BasePluginManager.get_instance()
        # check to see if it isn't a filename directly:
        if not os.path.isfile(filename):
            # Allow URL names here; make temp file if necessary
            url = urlparse(filename)
            if url.scheme != "":
                if url.scheme == "file":
                    filename = url2pathname(filename[7:])
                else:
                    url_fp = urlopen(filename) # open URL
                    # make a temp local file:
                    ext = os.path.splitext(url.path)[1]
                    fd, filename = tempfile.mkstemp(suffix=ext)
                    temp_fp = os.fdopen(fd, "w")
                    # read from URL:
                    data = url_fp.read()
                    # write locally:
                    temp_fp.write(data)
                    url_fp.close()
                    from  gramps.gen.db.dbconst import BDBVERSFN
                    versionpath = os.path.join(name, BDBVERSFN)
                    _LOG.debug("Write version %s", str(dbase.version()))
                    with open(versionpath, "w") as version_file:
                        version_file.write(str(dbase.version()))
                    temp_fp.close()

        (name, ext) = os.path.splitext(os.path.basename(filename))
        format = ext[1:].lower()

        for plugin in pmgr.get_import_plugins():
            if format == plugin.get_extension():

                new_path, name = self._create_new_db(name, edit_entry=False)

                # Create a new database
                self.__start_cursor(_("Importing data..."))

                dbid = "dbapi" ## config.get('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