Пример #1
0
    def __delitem__(self, plugin_name):
        """Remove a plugin from the manager."""
        # Is the plugin in the dictionary?
        if plugin_name not in self:

            # Do nothing
            return

        # Print a message about the plugin being unloaded
        self.logger.log_message(self.prefix + self.translations[
            'Unloading'].get_string(plugin=plugin_name))

        # Does the plugin have an unload function?
        if 'unload' in self[plugin_name].globals:

            # Use a try/except here to still allow the plugin to be unloaded
            try:

                # Call the plugin's unload function
                self[plugin_name].globals['unload']()

            # Was an exception raised?
            except:

                # Print the error to console, but
                # allow the plugin to still be unloaded
                except_hooks.print_exception()

        # Remove all modules from sys.modules
        self._remove_modules(plugin_name)

        # Remove the plugin from the dictionary
        super().__delitem__(plugin_name)
Пример #2
0
    def __delitem__(self, plugin_name):
        """Remove a plugin from the manager."""
        # Is the plugin in the dictionary?
        if plugin_name not in self:

            # Do nothing
            return

        # Print a message about the plugin being unloaded
        self.logger.log_message(self.prefix +
                                self.translations['Unloading'].get_string(
                                    plugin=plugin_name))

        # Does the plugin have an unload function?
        if 'unload' in self[plugin_name].globals:

            # Use a try/except here to still allow the plugin to be unloaded
            try:

                # Call the plugin's unload function
                self[plugin_name].globals['unload']()

            # Was an exception raised?
            except:

                # Print the error to console, but
                # allow the plugin to still be unloaded
                except_hooks.print_exception()

        # Remove all modules from sys.modules
        self._remove_modules(plugin_name)

        # Remove the plugin from the dictionary
        super().__delitem__(plugin_name)
Пример #3
0
 def _unload_auto_unload_instances(instances):
     for instance in instances:
         try:
             instance._unload_instance()
         except:
             # TODO: make this gungame specific
             except_hooks.print_exception()
Пример #4
0
    def _remove_modules(self, plugin_name):
        """Remove all modules from the plugin."""
        # Get the plugins import path
        base_name = self.base_import + plugin_name

        # Remove modules from sys.modules
        for module in list(sys.modules):
            if self._is_related_module(base_name, module):
                del sys.modules[module]

        # Unload AutoUnload instances
        for module, instances in list(_module_instances.items()):
            if not self._is_related_module(base_name, module):
                continue

            for instance in instances:
                try:
                    instance._unload_instance()
                except NotImplementedError:
                    # Print the error to console, but allow all
                    # other AutoUnload instances to be unloaded
                    # and the plugin to be fully unloaded itself
                    except_hooks.print_exception()

            del _module_instances[module]
Пример #5
0
    def _remove_module(module):
        """Remove a module and unloads any AutoUnload instances."""
        # Loop through all items in the module
        for name in dir(sys.modules[module]):

            # Get the item's object
            instance = getattr(sys.modules[module], name)

            # Is the object an AutoUnload instance
            if not isinstance(instance, AutoUnload):

                # No need to do anything with this object
                continue

            # Is the instance native to the given module?
            if instance._calling_module == module:

                # Use try/except in-case the instance
                # does not have an _unload_instance method
                try:

                    # Unload the object
                    instance._unload_instance()

                # Was a NotImplementedError encountered?
                except NotImplementedError:

                    # Print the error to console, but allow all
                    # other AutoUnload instances to be unloaded
                    # and the plugin to be fully unloaded itself
                    except_hooks.print_exception()

        # Delete the module
        del sys.modules[module]
Пример #6
0
def _build_plugin_docs(package):
    """Build Sphinx project files for a plugin."""
    project = SphinxProject(
        PLUGIN_PATH / package, PLUGIN_DOCS_PATH / package)
    if project.project_exists():
        if not plugin_manager.is_loaded(package):
            logger.log_message(
                'Plugin must be loaded to build the project files.')
            return

        try:
            project.build()
        except:
            except_hooks.print_exception()
            logger.log_message(
                'An error occured while building project ' +
                'files for plugin "{0}".'.format(package))
        else:
            logger.log_message(
                'Project files have been built for ' +
                'plugin "{0}".'.format(package))
    else:
        logger.log_message(
            'Sphinx project does not exist for ' +
            'plugin "{0}".'.format(package))
Пример #7
0
    def _load_categories_and_values(self, config):
        value_categories = OrderedDict()

        for category, data in config['categories'].items():
            if not category.startswith('_'):
                for name in data:
                    if not name.startswith('_'):
                        if self._is_valid_value_file(name):
                            if name not in value_categories:
                                value_categories[name] = []

                            value_categories[name].append(category)

        for name in config[self._module_name]:
            if not name.startswith('_'):
                if self._is_valid_value_file(name):
                    if name not in value_categories:
                        value_categories[name] = []

                        # Just to add it to the menu
                        value_categories[name].append(None)

        for name, categories in value_categories.items():
            try:
                setting = self.load(name)
            except:
                except_hooks.print_exception()
            else:
                for category in categories:
                    setting.add_to_category(category)
Пример #8
0
    def __call__(self, *args):
        """Verify the player's authorization."""
        # Does the player's authorization need to be checked?
        if self.check_auth:

            # Is the player authorized?
            if not auth_manager.is_player_authorized(
                playerinfo_from_index(args[1]), self.level, self.permission,
                    self.flag):

                # Is there fail callback?
                if self.fail_callback is not None:

                    # Use try/except in case the fail
                    # callback encounters an error
                    try:

                        # Call the fail callback
                        self.fail_callback(*args)

                    # Was an error encountered?
                    except:

                        # Print the exception to the console
                        except_hooks.print_exception()

                # Return a False value, since the player is not authorized
                return False

        # Call the callback and return its value
        return self.callback(*args)
Пример #9
0
    def __call__(self, *args):
        """Verify the player's authorization."""
        # Does the player's authorization need to be checked?
        if self.check_auth:

            # Is the player authorized?
            if not auth_manager.is_player_authorized(
                    playerinfo_from_index(args[1]), self.level,
                    self.permission, self.flag):

                # Is there fail callback?
                if self.fail_callback is not None:

                    # Use try/except in case the fail
                    # callback encounters an error
                    try:

                        # Call the fail callback
                        self.fail_callback(*args)

                    # Was an error encountered?
                    except:

                        # Print the exception to the console
                        except_hooks.print_exception()

                # Return a False value, since the player is not authorized
                return False

        # Call the callback and return its value
        return self.callback(*args)
Пример #10
0
    def __call__(self, *args):
        """Call all callbacks for the command."""
        # Loop through each callback in the list
        for callback in self:

            # Use try/except to continue the loop in case of an error
            try:

                # Call the callback and get its return value
                return_value = callback(*args)

            # Was an error encountered?
            except:

                # Print the exception to the console
                except_hooks.print_exception()

            # Was no error encountered?
            else:

                # Does the command need blocked?
                if not (return_value is None or return_value):

                    # Block the command
                    return CommandReturn.BLOCK

        # Allow the command to continue
        return CommandReturn.CONTINUE
    def print_warning(
            self, message, category, filename, lineno, file=None, line=None):
        """Called when a warning is encountered.

        This method hooks :obj:`warnings.showwarning` to log all warnings
        and call registered callbacks with the provided arguments.
        """
        # Loop through each callback in the warning list
        for callback in self:

            # Try to call the callback
            try:

                # Call the callback
                callback(message, category, filename, lineno)

            # Was an error encountered?
            except:

                # Log the exception
                except_hooks.print_exception()

        # Get the message to log
        print_message = '\n[SP] ' + _hooks_strings['Warning'].get_string()

        # Add the warning to the message
        print_message += "\n  File '..{0}', line {1}: {2}\n    {3}".format(
            filename.replace(GAME_PATH, ''), lineno,
            category.__name__, '\n'.join(_text_wrapper.wrap(str(message))))

        # Log the warning
        hooks_warnings_logger.log_warning(print_message + '\n')
Пример #12
0
    def _remove_modules(self, plugin_name):
        """Remove all modules from the plugin."""
        # Get the plugins import path
        base_name = self.base_import + plugin_name

        # Remove modules from sys.modules
        for module in list(sys.modules):
            if self._is_related_module(base_name, module):
                del sys.modules[module]

        # Unload AutoUnload instances
        for module, instances in list(_module_instances.items()):
            if not self._is_related_module(base_name, module):
                continue

            for instance in instances:
                try:
                    instance._unload_instance()
                except NotImplementedError:
                    # Print the error to console, but allow all
                    # other AutoUnload instances to be unloaded
                    # and the plugin to be fully unloaded itself
                    except_hooks.print_exception()

            del _module_instances[module]
Пример #13
0
 def _tick(self):
     """Internal tick listener."""
     current_time = time.time()
     while self and self[0].exec_time <= current_time:
         try:
             self.pop(0).execute()
         except:
             except_hooks.print_exception()
Пример #14
0
 def _tick(self):
     """Internal tick listener."""
     current_time = time.time()
     while self and self[0].exec_time <= current_time:
         try:
             self.pop(0).execute()
         except:
             except_hooks.print_exception()
Пример #15
0
 def _unload_auto_unload_instances(instances):
     for instance in instances:
         try:
             instance._unload_instance()
         # pylint: disable=broad-except
         except Exception:
             # TODO: make this gungame specific
             except_hooks.print_exception()
Пример #16
0
    def remove(self, ward):
        super().remove(ward)

        try:
            ward.on_removed()
        except:
            except_hooks.print_exception()

        if not self:
            self._repeat.stop()
Пример #17
0
    def append(self, ward):
        if not self:
            self._repeat.start(0.1)

        try:
            ward.on_spawned()
        except:
            except_hooks.print_exception()

        super().append(ward)
Пример #18
0
 def _unload_auto_unload_instances(instances):
     """Unload all given :class:`AutoUnload` instances."""
     for instance in instances:
         try:
             instance._unload_instance()
         except:
             # Print the error to console, but allow all
             # other AutoUnload instances to be unloaded
             # and the plugin to be fully unloaded itself
             except_hooks.print_exception()
Пример #19
0
 def _unload_auto_unload_instances(instances):
     """Unload all given :class:`AutoUnload` instances."""
     for instance in instances:
         try:
             instance._unload_instance()
         except:
             # Print the error to console, but allow all
             # other AutoUnload instances to be unloaded
             # and the plugin to be fully unloaded itself
             except_hooks.print_exception()
Пример #20
0
    def __missing__(self, plugin_name):
        """Try to load a plugin that is not loaded."""
        # Try to get the plugin's instance
        try:

            # Get the plugin's instance
            instance = self.instance(plugin_name, self.base_import)

            # Does the plugin have a load function?
            if 'load' in instance.globals:

                # Call the plugin's load function
                instance.globals['load']()

        # Was the file not found?
        # We use this check because we already printed the error to console
        except PluginFileNotFoundError:

            # Return None as the value to show the plugin was not loaded
            return None

        # Was a different error encountered?
        except:

            # Get the error
            error = sys.exc_info()

            # Is the error due to "No module named '<plugin>.<plugin>'"?
            if (len(error[1].args) and error[1].args[0]
                    == "No module named '{0}.{0}'".format(plugin_name)):

                # Print a message about not using built-in module names
                # We already know the path exists, so the only way this error
                # could occur is if it shares its name with a built-in module
                self.logger.log_message(
                    self.prefix + self.translations['Built-in'].get_string(
                        plugin=plugin_name))

            # Otherwise
            else:

                # Print the exception to the console
                except_hooks.print_exception(*error)

                # Remove all modules from sys.modules
                self._remove_modules(plugin_name)

            # Return None as the value to show the addon was not loaded
            return None

        # Add the plugin to the dictionary with its instance
        self[plugin_name] = instance

        # Return the give instance
        return instance
Пример #21
0
    def __missing__(self, plugin_name):
        """Try to load a plugin that is not loaded."""
        # Try to get the plugin's instance
        try:

            # Get the plugin's instance
            instance = self.instance(plugin_name, self.base_import)

            # Does the plugin have a load function?
            if 'load' in instance.globals:

                # Call the plugin's load function
                instance.globals['load']()

        # Was the file not found?
        # We use this check because we already printed the error to console
        except PluginFileNotFoundError:

            # Return None as the value to show the plugin was not loaded
            return None

        # Was a different error encountered?
        except:

            # Get the error
            error = sys.exc_info()

            # Is the error due to "No module named '<plugin>.<plugin>'"?
            if (len(error[1].args) and error[1].args[0] ==
                    "No module named '{0}.{0}'".format(plugin_name)):

                # Print a message about not using built-in module names
                # We already know the path exists, so the only way this error
                # could occur is if it shares its name with a built-in module
                self.logger.log_message(self.prefix + self.translations[
                    'Built-in'].get_string(plugin=plugin_name))

            # Otherwise
            else:

                # Print the exception to the console
                except_hooks.print_exception(*error)

                # Remove all modules from sys.modules
                self._remove_modules(plugin_name)

            # Return None as the value to show the addon was not loaded
            return None

        # Add the plugin to the dictionary with its instance
        self[plugin_name] = instance

        # Return the give instance
        return instance
Пример #22
0
    def get_weapon_orders(self):
        """Retrieve all weapon orders and store them in the dictionary."""
        for file in GUNGAME_WEAPON_ORDER_PATH.files('*.txt'):
            try:
                self[file.namebase] = WeaponOrder(file)
            except WeaponOrderError:
                # TODO: make this gungame specific
                except_hooks.print_exception()

        if not self:
            raise ValueError('No valid weapon order files found.')
Пример #23
0
def on_player_delete(wcsplayer):
    for ward in ward_manager:
        if ward.owner == wcsplayer:
            ward_manager.remove(ward)
        elif wcsplayer in ward.entities:
            try:
                ward.on_disconnect(wcsplayer)
            except:
                except_hooks.print_exception()

            del ward.entities[wcsplayer]
Пример #24
0
    def _request_receive(self, value):
        self.data['_internal_input_delay'].cancel()

        try:
            accepted = self.data['_internal_input_callback'](self, value)
        except:
            except_hooks.print_exception()
        else:
            if not accepted:
                input_invalid_message.send(self.index, value=value)
        finally:
            self._request_end()
Пример #25
0
    def __exit__(self, exctype, value, trace_back):
        """Used when exiting "with" context management to create the cvar."""
        # Was an exception raised?
        if trace_back:

            # Print the exception
            except_hooks.print_exception(exctype, value, trace_back)

            # Return
            return False

        # Return
        return True
Пример #26
0
    def __exit__(self, exctype, value, trace_back):
        """Used when exiting "with" context management to create the cvar."""
        # Was an exception raised?
        if trace_back:

            # Print the exception
            except_hooks.print_exception(exctype, value, trace_back)

            # Return
            return False

        # Return
        return True
Пример #27
0
def parse_ini_items():
    items = OrderedDict()

    if (CFG_PATH / 'items.ini').isfile():
        imported = ConfigObj(CFG_PATH / 'items.ini')

        for category in imported:
            fixed_category = FIX_NAME.sub('', category.lower().replace(' ', '_'))

            if fixed_category not in item_manager._category_max_items:
                item_manager._category_max_items[fixed_category] = int(imported[category]['maxitems'])

            if fixed_category not in categories_strings:
                categories_strings[fixed_category] = _LanguageString(category)

            for name, data in imported[category].items():
                if name not in ('desc', 'maxitems'):
                    for alias, value in data.items():
                        if alias.startswith('shopalias_'):
                            if alias in _aliases:
                                if cfg_debug_alias_duplicate.get_float():
                                    warn(f'Alias "{alias}" is already registered')
                            else:
                                _aliases[alias] = value

                    try:
                        fixed_name = FIX_NAME.sub('', name.lower().replace(' ', '_'))
                        settings = items[fixed_name] = ImportedItem(fixed_name, ModuleType.ESS_INI)

                        settings.cmds['activatecmd'] = data['cmdactivate']
                        settings.cmds['buycmd'] = data['cmdbuy']

                        settings.config['cost'] = int(data['cost'])
                        settings.config['required'] = int(data['level'])
                        settings.config['dab'] = int(data['dab'])
                        settings.config['duration'] = int(data['duration'])
                        settings.config['count'] = int(data['max'])
                        settings.config['event'] = [data['cfg']]

                        settings.strings['name'] = _LanguageString(data['name'])
                        settings.strings['description'] = _LanguageString(data['desc'].replace(r'\n', ''))

                        settings.add_to_category(fixed_category)
                    except:
                        warn(f'Unable to properly parse the item "{name}" due to the following exception:')
                        except_hooks.print_exception()
                        continue
                    else:
                        items[fixed_name] = settings

    return items
Пример #28
0
    def run(self):
        self.con = None
        self.cur = None

        self.connect()

        while True:
            query, arguments, callback, many, keywords = _queue.get()

            if query is None:
                if callback is None:
                    break

                result = _Result(args=keywords)

                _output.put((callback, result))

                if _queue.empty():
                    if self.con is not None and self.cur is not None:
                        self.close()

                continue

            if self.con is None or self.cur is None:
                self.connect()

            result = _Result(args=keywords, query=query)

            try:
                if many:
                    self.cur.executemany(query, arguments)
                else:
                    self.cur.execute(query, arguments)
            except:
                except_hooks.print_exception()
                result._exception = exc_info()

            if callback is not None:
                result._data = self.cur.fetchall()

            if not (result.exception is None and callback is None):
                _output.put((callback, result))

            if _queue.empty():
                self.close()

        if self.con is not None and self.cur is not None:
            self.close()

        _output.put((True, True))
Пример #29
0
    def __exit__(self, exctype, value, trace_back):
        """Fire the event on exit, unless an exception was encountered."""
        # Was an exception raised?
        if trace_back:

            # Print the exception
            except_hooks.print_exception(exctype, value, trace_back)

            # Return
            return False

        # Fire the event
        self.fire()

        # Return
        return True
Пример #30
0
    def fire_game_event(self, game_event):
        """Loop through all callbacks for an event and calls them."""
        # Loop through each callback in the event's list
        for callback in self:

            # Try to call the callback
            try:

                # Call the callback
                callback(game_event)

            # Was an error encountered?
            except:

                # Print the exception to the console
                except_hooks.print_exception()
Пример #31
0
    def fire_game_event(self, game_event):
        """Loop through all callbacks for an event and calls them."""
        # Loop through each callback in the event's list
        for callback in self:

            # Try to call the callback
            try:

                # Call the callback
                callback(game_event)

            # Was an error encountered?
            except:

                # Print the exception to the console
                except_hooks.print_exception()
Пример #32
0
    def __exit__(self, exctype, value, trace_back):
        """Fire the event on exit, unless an exception was encountered."""
        # Was an exception raised?
        if trace_back:

            # Print the exception
            except_hooks.print_exception(exctype, value, trace_back)

            # Return
            return False

        # Fire the event
        self.fire()

        # Return
        return True
Пример #33
0
def raceinfo_detail_menu_build(menu, client):
    wcsplayer = Player(client)
    name = wcsplayer.data['_internal_raceinfo']
    settings = race_manager[name]

    all_races = race_manager._category_to_values[wcsplayer.data.get(
        '_internal_raceinfo_category')]

    if name not in all_races:
        all_races = race_manager._category_to_values[None]

    try:
        index = all_races.index(name)
    except IndexError:
        index = None
        except_hooks.print_exception()

    menu[0].text.tokens['name'] = settings.strings['name']
    menu[0].text.tokens['place'] = -1 if index is None else index + 1
    menu[0].text.tokens['total'] = len(all_races)
    menu[1].text.tokens['required'] = settings.config['required']
    menu[2].text.tokens['maximum'] = settings.config['maximum']
    menu[3].text.tokens['name'] = settings.config['author']

    if settings.config['allowonly']:
        if wcsplayer._baseplayer.steamid2 in settings.config[
                'allowonly'] or wcsplayer._baseplayer.steamid3 in settings.config[
                    'allowonly']:
            menu[4].text = menu_strings['raceinfo_detail_menu private allowed']
        elif 'VIP' in settings.config[
                'allowonly'] and wcsplayer.privileges.get('vip_raceaccess'):
            menu[4].text = menu_strings['raceinfo_detail_menu private allowed']
        elif 'ADMIN' in settings.config[
                'allowonly'] and wcsplayer.privileges.get('admin_raceaccess'):
            menu[4].text = menu_strings['raceinfo_detail_menu private allowed']
        else:
            menu[4].text = menu_strings['raceinfo_detail_menu private']
    else:
        menu[4].text = menu_strings['raceinfo_detail_menu public']

    menu[5].text.tokens['count'] = len(settings.config['skills'])

    menu[7].selectable = menu[
        7].highlight = False if index is None else index != 0
    menu[8].selectable = menu[
        8].highlight = False if index is None else index != len(all_races) - 1
Пример #34
0
    def _tick(self):
        for _ in range(16):
            if _output.empty():
                break

            callback, result = _output.get_nowait()

            if callback is True and result is True:
                _repeat.stop()
            else:
                if callback is not None:
                    try:
                        callback(result)
                    except:
                        except_hooks.print_exception()

                if result.exception:
                    except_hooks.print_exception(*result.exception)
Пример #35
0
def _create_source_python_docs():
    """Create a Sphinx project for Source.Python."""
    project = SphinxProject(SP_PACKAGES_PATH, SP_DOCS_PATH)
    if project.project_exists():
        logger.log_message(
            'Sphinx project already exists for Source.Python')
    else:
        try:
            project.create(
                'Source.Python Development Team', 'Source.Python', VERSION)
        except:
            except_hooks.print_exception()
            logger.log_message(
                'An error occured while creating Sphinx ' +
                'project for Source.Python.')
        else:
            logger.log_message(
                'Sphinx project has been created for Source.Python.')
Пример #36
0
    def __call__(self):
        """Call the delay with the proper arguments and keywords."""
        # Log the call message
        listeners_tick_delays_logger.log_debug(
            'Delay.__call__ - Try to call - <{0}> <{1}> <{2}>'.format(
                self.callback, self.args, self.kwargs))

        # Use try/except in case an error is encountered
        try:

            # Execute the callback with the arguments and keywords
            self.callback(*self.args, **self.kwargs)

        # Was an error encountered?
        except:

            # Print the exception to the console
            except_hooks.print_exception()
Пример #37
0
def _create_plugin_docs(package):
    """Create a Sphinx project for a plugin."""
    project = SphinxProject(
        PLUGIN_PATH / package, PLUGIN_DOCS_PATH / package)
    if project.project_exists():
        logger.log_message(
            'Sphinx project already exists for ' +
            'plugin "{0}".'.format(package))
    else:
        try:
            project.create('Unknown')
        except:
            except_hooks.print_exception()
            logger.log_message(
                'An error occured while creating Sphinx project ' +
                'for plugin "{0}".'.format(package))
        else:
            logger.log_message(
                'Sphinx project has been created for' +
                ' plugin "{0}".'.format(package))
Пример #38
0
def _generate_plugin_docs(package):
    """Generate Sphinx project files for a plugin."""
    project = SphinxProject(
        PLUGIN_PATH / package, PLUGIN_DOCS_PATH / package)
    if project.project_exists():
        try:
            project.generate_project_files()
        except:
            except_hooks.print_exception()
            logger.log_message(
                'An error occured while generating project ' +
                'files for plugin "{0}".'.format(package))
        else:
            logger.log_message(
                'Project files have been generated ' +
                'for plugin "{0}".'.format(package))
    else:
        logger.log_message(
            'Sphinx project does not exist for' +
            ' plugin "{0}".'.format(package))
Пример #39
0
    def execute(self, name, event=None, define=False):
        if self.settings.type is ModuleType.SP:
            callback = _item_callbacks.get(self.name, {}).get(name)

            if callback is not None:
                if event is None:
                    callback(self.wcsplayer)
                else:
                    callback(event, self.wcsplayer)
        elif self.settings.type is ModuleType.ESP:
            callback = es.addons.Blocks.get(f'wcs/modules/items/{self.name}/{name}')

            if callback is not None:
                if event is None:
                    callback(self.wcsplayer)
                else:
                    callback(es.event_var, self.wcsplayer)
        elif self.settings.type is ModuleType.ESS:
            addon = esc.addons.get(f'wcs/modules/items/{self.name}')

            if addon is not None:
                executor = addon.blocks.get(name)

                if executor is not None:
                    if define:
                        cvar_wcs_userid.set_int(self.wcsplayer.userid)

                    executor.run()
        elif self.settings.type is ModuleType.ESS_INI or self.settings.type is ModuleType.ESS_KEY:
            commands = self.settings.cmds.get(name)

            if commands is not None and commands:
                if define:
                    cvar_wcs_userid.set_int(self.wcsplayer.userid)

                for cmd in commands.split(';'):
                    try:
                        execute_server_command(*split(cmd))
                    except ValueError:
                        except_hooks.print_exception()
                        break
Пример #40
0
def _create_custom_package_docs(package):
    """Create a Sphinx project for a custom package."""
    project = SphinxProject(
        CUSTOM_PACKAGES_PATH / package,
        CUSTOM_PACKAGES_DOCS_PATH / package)
    if project.project_exists():
        logger.log_message(
            'Sphinx project already exists for custom' +
            ' package "{0}".'.format(package))
    else:
        try:
            project.create('Unknown')
        except:
            except_hooks.print_exception()
            logger.log_message(
                'An error occured while creating Sphinx project for ' +
                'custom package "{0}".'.format(package))
        else:
            logger.log_message(
                'Sphinx project has been created for' +
                ' custom package "{0}".'.format(package))
Пример #41
0
def _build_custom_package_docs(package):
    """Build Sphinx project files for a custom package."""
    project = SphinxProject(
        CUSTOM_PACKAGES_PATH / package,
        CUSTOM_PACKAGES_DOCS_PATH / package)
    if project.project_exists():
        try:
            project.build()
        except:
            except_hooks.print_exception()
            logger.log_message(
                'An error occured while building project ' +
                'files for custom package "{0}".'.format(package))
        else:
            logger.log_message(
                'Project files have been built for ' +
                'custom package "{0}".'.format(package))
    else:
        logger.log_message(
            'Sphinx project does not exist for ' +
            'custom package "{0}".'.format(package))
Пример #42
0
def _generate_source_python_docs():
    """Generate Sphinx project files for Source.Python."""
    project = SphinxProject(SP_PACKAGES_PATH, SP_DOCS_PATH)
    if project.project_exists():
        try:
            project.generate_project_files('developing/modules')
        except:
            except_hooks.print_exception()
            logger.log_message(
                'An error occured while generating ' +
                'project files for Source.Python')
        else:
            modules_dir = project.project_source_dir / 'developing' / 'modules'
            modules_dir.joinpath('modules.rst').remove()
            for file_path in modules_dir.files('source-python.*.rst'):
                _prepare_generated_source_python_file(file_path)

            logger.log_message(
                'Project files have been generated for Source.Python.')
    else:
        logger.log_message(
            'Sphinx project does not exist for Source.Python.')
Пример #43
0
    def unload(self, plugin_name):
        """Unload a plugin by name.

        :param str plugin_name:
            Name of the plugin to unload.
        :raise PluginNotLoaded:
            Raised if the plugin is not loaded.
        """
        if not self.is_loaded(plugin_name):
            raise PluginNotLoaded(
                'Plugin "{}" is not loaded.'.format(plugin_name))

        plugin = self[plugin_name]
        on_plugin_unloading_manager.notify(plugin)
        try:
            plugin._unload()
        except:
            except_hooks.print_exception()

        self._remove_modules(plugin_name)
        del self[plugin_name]
        on_plugin_unloaded_manager.notify(plugin)
    def unload(self, plugin_name):
        """Unload a plugin by name.

        :param str plugin_name:
            Name of the plugin to unload.
        :raise PluginNotLoaded:
            Raised if the plugin is not loaded.
        """
        if not self.is_loaded(plugin_name):
            raise PluginNotLoaded(
                'Plugin "{}" is not loaded.'.format(plugin_name))

        plugin = self[plugin_name]
        on_plugin_unloading_manager.notify(plugin)
        try:
            plugin._unload()
        except:
            except_hooks.print_exception()

        self._remove_modules(plugin_name)
        del self[plugin_name]
        on_plugin_unloaded_manager.notify(plugin)
Пример #45
0
    def _tick(self):
        if not _output.empty():
            value = _output.get_nowait()

            decrease = value[0]
            listener = value[1]

            if listener is not None:
                try:
                    listener(*value[2:])
                except:
                    except_hooks.print_exception()

            if decrease:
                self._counter -= 1

                if not self._counter:
                    self._repeat.stop()

            for thread in self._threads.copy():
                if not thread.is_alive():
                    self._threads.remove(thread)
Пример #46
0
    def load_plugin(self, plugin_name):
        """Load a plugin by name.

        :param str plugin_name:
            Name of the plugin to load.
        :return:
            Return the loaded plugin. Return ``None`` on failure.
        :rtype: Plugin
        """
        plugin = None
        self.log_message(
            self.translations['Loading'].get_string(plugin=plugin_name))
        try:
            plugin = self.manager.load(plugin_name)
        except InvalidPluginName:
            self.log_message(self.translations['Invalid Name'].get_string(
                plugin=plugin_name))
        except PluginAlreadyLoaded:
            self.log_message(self.translations['Already Loaded'].get_string(
                plugin=plugin_name))
        except PluginFileNotFoundError:
            self.log_message(self.translations['No Module'].get_string(
                plugin=plugin_name,
                file=GAME_PATH.relpathto(
                    self.manager.get_plugin_file_path(plugin_name)).replace(
                        '\\', '/')))
        except PluginHasBuiltInName:
            self.log_message(
                self.translations['Built-in'].get_string(plugin=plugin_name))
        except:
            except_hooks.print_exception()
            self.log_message(self.translations['Unable to Load'].get_string(
                plugin=plugin_name))
        else:
            self.log_message(self.translations['Successful Load'].get_string(
                plugin=plugin_name))

        return plugin
Пример #47
0
def _build_source_python_docs():
    """Build Sphinx project files for Source.Python."""
    project = SphinxProject(SP_PACKAGES_PATH, SP_DOCS_PATH)
    if project.project_exists():
        # Update version and release
        conf_file = project.project_source_dir / 'conf.py'
        with conf_file.open() as f:
            lines = f.readlines()

        # Get the version string
        version = '' if is_unversioned() else f'v{VERSION}'

        with conf_file.open('w') as f:
            for line in lines:
                if line.startswith(('version', 'release')):
                    line = '{0} = \' {1}\'\n'.format(
                        line.split(maxsplit=1)[0], version)

                f.write(line)

        # Create/update credits.rst
        with project.project_source_dir.joinpath(
                'general', 'credits.rst').open('w') as f:
            f.write(_get_updated_credits_wiki())

        try:
            project.build()
        except:
            except_hooks.print_exception()
            logger.log_message(
                'An error occured while building ' +
                'project files for Source.Python.')
        else:
            logger.log_message(
                'Project files have been built for Source.Python.')
    else:
        logger.log_message(
            'Sphinx project does not exist for Source.Python.')
    def load_plugin(self, plugin_name):
        """Load a plugin by name.

        :param str plugin_name:
            Name of the plugin to load.
        :return:
            Return the loaded plugin. Return ``None`` on failure.
        :rtype: Plugin
        """
        plugin = None
        self.log_message(self.translations[
            'Loading'].get_string(plugin=plugin_name))
        try:
            plugin = self.manager.load(plugin_name)
        except InvalidPluginName:
            self.log_message(self.translations[
                'Invalid Name'].get_string(plugin=plugin_name))
        except PluginAlreadyLoaded:
            self.log_message(self.translations[
                'Already Loaded'].get_string(plugin=plugin_name))
        except PluginFileNotFoundError:
            self.log_message(self.translations[
                'No Module'].get_string(
                    plugin=plugin_name, file=GAME_PATH.relpathto(
                        self.manager.get_plugin_file_path(
                            plugin_name)).replace('\\', '/')))
        except PluginHasBuiltInName:
            self.log_message(self.translations[
                'Built-in'].get_string(plugin=plugin_name))
        except:
            except_hooks.print_exception()
            self.log_message(self.translations[
                'Unable to Load'].get_string(plugin=plugin_name))
        else:
            self.log_message(self.translations[
                'Successful Load'].get_string(plugin=plugin_name))

        return plugin
Пример #49
0
def _pre_game_event(args):
    """Call pre-event functions if the event is registered."""
    # Get the GameEvent object
    game_event = make_object(GameEvent, args[1])

    # Get the name of the event
    event_name = game_event.name

    # If the current event is not in the dictionary, return
    if event_name not in pre_event_manager:
        return

    # Create a variable to know what to do after all pre-events are called
    event_action = EventAction.CONTINUE

    # Loop through all callbacks in the pre-event's list
    for callback in pre_event_manager[event_name]:

        # Use try/except in case an error occurs during in the callback
        try:

            # Call the callback and get its return value
            current_action = callback(game_event)

            # Is the return value invalid?
            if (current_action is not None and
                    not isinstance(current_action, EventAction)):

                # Raise an error to exit the try
                raise ValueError(
                    'Invalid return value for pre-event "{0}".'.format(
                        current_action))

        # Was an error encountered?
        except:

            # Print the exception to the console
            except_hooks.print_exception()

        # Was no error encountered?
        else:

            # Does the current action have a higher priority?
            if current_action is not None and current_action > event_action:

                # Change the event action
                event_action = current_action

    # Does the return value want to set the dontbroadcast value?
    if event_action is EventAction.STOP_BROADCAST:

        # Set the dontbroadcast value
        args[2] = True

    # Does the return value want to block the event?
    elif event_action is EventAction.BLOCK:

        # Free the event
        game_event_manager.free_event(game_event)

        # Block the event
        return False
Пример #50
0
    def _send_message(self, recipient, **kwargs):
        """Send the message to the given recipient filter."""
        # Get a UserMessage instance
        usermsg = UserMessage(recipient, self._message_name)

        # Loop through all required parameters
        for parameter_name in self._required_parameters:

            # Get the current parameter data
            parameter_data = self._required_parameters[parameter_name]

            # Get the current parameter length
            parameter_length = parameter_data['length']

            # Is the current parameter larger than one value?
            if parameter_length > 1:

                # Try to prepare the current parameter values
                try:

                    # Prepare the given values
                    parameter_values = self._prepare_parameter(
                        parameter_name, kwargs[parameter_name])

                # I'm not really fan of this but, to prevent crashes, we need
                #   to hook any exceptions that may occurs...
                except:

                    # Print the exception to the console
                    except_hooks.print_exception()

                    # Print a debugging message
                    echo_console(
                        '"{0}" is not a valid value for "{1}.{2}"'.format(
                            kwargs[parameter_name],
                            self._message_name,
                            parameter_name))

                    # Use the default values
                    parameter_values = self._prepare_parameter(
                        parameter_name, parameter_data['default_values'])

                # Get the current parameter field name
                field_name = parameter_data['field_name']

                # Loop through all values
                for parameter_index, parameter_type, parameter_value in zip(
                    range(parameter_length), parameter_data['types'],
                        parameter_values):

                    # Write the current parameter
                    self._write_field_value(
                        parameter_name, usermsg, parameter_type,
                        field_name, parameter_value, parameter_index)

            # Otherwise
            else:

                # Try to convert the given value
                try:

                    # Prepare the current parameter
                    parameter_value = self._prepare_parameter(
                        parameter_name, kwargs[parameter_name])

                # I'm not really fan of this but, to prevent crashes, we need
                #   to hook any exceptions that may occurs...
                except:

                    # Print the exception to the console
                    except_hooks.print_exception()

                    # Print a debugging message
                    echo_console(
                        '"{0}" is not a valid value for "{1}.{2}"'.format(
                            kwargs[parameter_name],
                            self._message_name,
                            parameter_name))

                    # Use the default value
                    parameter_value = self._prepare_parameter(
                        parameter_name, parameter_data['default_value'])

                # Write the current parameter
                self._write_field_value(
                    parameter_name, usermsg, parameter_data['type'],
                    parameter_data['field_name'], parameter_value)

        # Send the message
        usermsg.send_message()