Esempio n. 1
0
    def write(self):
        self.file.write('#compdef mktap\n')
        self.file.write('_mktap_subcmds=(\n')
        from twisted import plugin as newplugin
        from twisted.scripts.mktap import IServiceMaker
        plugins = newplugin.getPlugins(IServiceMaker)

        for p in plugins:
            self.file.write('"%s:%s"\n' % (p.tapname, p.description))
        self.file.write(")\n\n")

        self.optionsClass.zsh_extras = ['*::subcmd:->subcmd']
        gen = ArgumentsGenerator(self.cmd_name, self.optionsClass, self.file)
        gen.write()

        self.file.write("""if (( CURRENT == 1 )); then
  _describe "tap to build" _mktap_subcmds && ret=0
fi
(( ret )) || return 0

service="$words[1]"

case $service in\n""")

        plugins = newplugin.getPlugins(IServiceMaker)
        for p in plugins:
            self.file.write(p.tapname + ")\n")
            gen = ArgumentsGenerator(p.tapname, p.options, self.file)
            gen.write()
            self.file.write(";;\n")
        self.file.write("""*) _message "don't know how to complete $service";;\nesac""")
Esempio n. 2
0
    def test_detectFilesChanged(self):
        """
        Check that if the content of a plugin change, L{plugin.getPlugins} is
        able to detect the new plugins added.
        """
        FilePath(__file__).sibling('plugin_extra1.py'
            ).copyTo(self.package.child('pluginextra.py'))
        try:
            plgs = list(plugin.getPlugins(ITestPlugin, self.module))
            # Sanity check
            self.assertEquals(len(plgs), 2)

            FilePath(__file__).sibling('plugin_extra2.py'
                ).copyTo(self.package.child('pluginextra.py'))

            # Fake out Python.
            self._unimportPythonModule(sys.modules['mypackage.pluginextra'])

            # Make sure additions are noticed
            plgs = list(plugin.getPlugins(ITestPlugin, self.module))

            self.assertEquals(len(plgs), 3)

            names = ['TestPlugin', 'FourthTestPlugin', 'FifthTestPlugin']
            for p in plgs:
                names.remove(p.__name__)
                p.test1()
        finally:
            self._unimportPythonModule(
                sys.modules['mypackage.pluginextra'],
                True)
Esempio n. 3
0
    def write(self):
        """
        Write the completion function to the file given to __init__
        @return: C{None}
        """
        self.file.write('#compdef %s\n' % (self.cmd_name,))
        self.file.write('local _zsh_subcmds_array\n_zsh_subcmds_array=(\n')
        from twisted import plugin as newplugin
        plugins = newplugin.getPlugins(self.interface)

        for p in plugins:
            self.file.write('"%s:%s"\n' % (p.tapname, p.description))
        self.file.write(")\n\n")

        self.options.__class__.zsh_extras = ['*::subcmd:->subcmd']
        gen = ArgumentsGenerator(self.cmd_name, self.options, self.file)
        gen.write()

        self.file.write("""if (( CURRENT == 1 )); then
  _describe "%s" _zsh_subcmds_array && ret=0
fi
(( ret )) || return 0

service="$words[1]"

case $service in\n""" % (self.subcmdLabel,))

        plugins = newplugin.getPlugins(self.interface)
        for p in plugins:
            self.file.write(p.tapname + ")\n")
            gen = ArgumentsGenerator(p.tapname, p.options(), self.file)
            gen.write()
            self.file.write(";;\n")
        self.file.write("*) _message \"don't know how to" \
                        " complete $service\";;\nesac")
Esempio n. 4
0
 def fromPlugins(cls, clock):
     """
     Create a :obj:`MimicCore` from all :obj:`IAPIMock` and
     :obj:`IAPIDomainMock` plugins.
     """
     service_catalog_plugins = getPlugins(IAPIMock, plugins)
     domain_plugins = getPlugins(IAPIDomainMock, plugins)
     return cls(clock, service_catalog_plugins, domain_plugins)
Esempio n. 5
0
    def test_detectFilesRemoved(self):
        """
        Check that when a dropin file is removed, L{plugin.getPlugins} doesn't
        return it anymore.
        """
        FilePath(__file__).sibling("plugin_extra1.py").copyTo(self.package.child("pluginextra.py"))
        try:
            # Generate a cache with pluginextra in it.
            list(plugin.getPlugins(ITestPlugin, self.module))

        finally:
            self._unimportPythonModule(sys.modules["mypackage.pluginextra"], True)
        plgs = list(plugin.getPlugins(ITestPlugin, self.module))
        self.assertEqual(1, len(plgs))
Esempio n. 6
0
 def _init_faf_events(self):
     """
     Generate classes and initializes listeners for 'system events'.
     Please use global registration as last resort.
     """
     for klass_name in events_lst + [evname for elst in getPlugins(IEventList, events) for evname in elst]:
         self.registerEventFromName(klass_name, Evt)
     # Register Listeners
     for event_handler in getPlugins(IEventListener, events):
         if not isinstance(event_handler.__class__.EVENT, list):
             self.addListener(event_handler.__class__.EVENT, event_handler)
         else:
             for event_name in event_handler.__class__.EVENT:
                 self.addListener(event_name, event_handler)
Esempio n. 7
0
    def _init_resp_events(self):
        full_lst = responding_events + [
            evname for elst in getPlugins(IRespondingEventList, 
                                events) for evname in elst
            ]

        for klass_name in  full_lst:
            self.registerEventFromName(klass_name, RespondingEvt)
        
        for event_handler in getPlugins(IEventResponder):
            if not isinstance(event_handler.__class__.RESPEVENT, list):
                self.addResponder(event_handler.__class__.RESPEVENT, event_handler.respond)
            else:
                for event_name in event_handler.__class__.RESPEVENT:
                    self.addResponder(event_name, event_handler.respond)
Esempio n. 8
0
    def postOptions(self):
        BaseOptions.postOptions(self)
        if self['running_author-whitelist']:
            self['author-whitelist'] = self['running_author-whitelist']
        else:
            self['author-whitelist'] = [ip_network(self['author-whitelist'], strict=False)]

        if self['running_subscriber-whitelist']:
            self['subscriber-whitelist'] = self['running_subscriber-whitelist']
        else:
            self['subscriber-whitelist'] = [ip_network(self['subscriber-whitelist'], strict=False)]

        if self['verbosity'] >= 2:
            log.LEVEL = log.Levels.DEBUG
        elif self['verbosity'] == 1:
            log.LEVEL = log.Levels.INFO
        else:
            log.LEVEL = log.Levels.WARNING

        # Now enable plugins if requested.
        # We loop over all plugins, checking if the user supplied their name
        # on the command line and adding them to our list of handlers if so.
        for plugin in getPlugins(IHandler, comet.plugins):
            if self[plugin.name]:
                if IHasOptions.providedBy(plugin):
                    for name, _, _ in plugin.get_options():
                        plugin.set_option(name, self["%s-%s" % (plugin.name, name)])
                self['handlers'].append(plugin)
Esempio n. 9
0
def retrieve_plugins(interface, cached=True, cache={}):
    """
    Look up all plugins for a certain interface.

    If the plugin cache is enabled, this function will not attempt to reload
    plugins from disk or discover new plugins.

    :param interface interface: the interface to use
    :param bool cached: whether to use the in-memory plugin cache

    :returns: a dict of plugins, keyed by name
    :raises PluginException: no plugins could be found for the given interface
    """

    if cached and interface in cache:
        return cache[interface]

    print "Discovering %s..." % interface
    d = {}
    for p in getPlugins(interface, beta.plugins):
        print " ~ Plugin: %s" % p.name
        d[p.name] = p

    cache[interface] = d
    return d
Esempio n. 10
0
    def loadAll(self) -> None:
        configModulesToLoad = self.bot.config.getWithDefault('modules', ['all'])
        moduleNamesToLoad = set()
        allModules = [module for module in getPlugins(IModule, desertbot.modules)]

        if 'all' in configModulesToLoad:
            moduleNamesToLoad.update(set([module.__class__.__name__ for module in allModules]))

        for module in configModulesToLoad:
            if module == 'all':
                continue
            elif module.startswith('-'):
                moduleNamesToLoad.remove(module[1:])
            else:
                moduleNamesToLoad.add(module)

        modulesToLoad = sorted([module for module in allModules if module.__class__.__name__ in moduleNamesToLoad],
                               key=lambda module: module.loadingPriority, reverse=True)
        for module in modulesToLoad:
            try:
                self.loadModule(module.__class__.__name__, rebuild_=False)
            except Exception as e:
                # ^ dirty, but we don't want any modules to kill the bot
                self.logger.exception("Exception when loading module {!r}".format(module))
                self.bot.reraiseIfDebug(e)
Esempio n. 11
0
    def activate(self):
        self.installable = []
        self.uninstallable = []
        installed = {}
        available = {}
        for i in self.store.query(InstalledPlugin):
            installed[i.path] = i.version

        for a in getPlugins(isqueal.ISquealPlugin, plugins):
            path = a.__name__ + "." + a.__module__
            available[path] = a

        for path, plugin in available.items():
            if path in installed:
                self.uninstallable.append({
                    'plugin': plugin,
                    'version': a.version,
                    'path': path
                })
                if plugin.version > installed[path]:
                    log.warning("Plugin %s has been upgraded" % path)
                elif plugin.version < installed[path]:
                    log.warning("Plugin %s has been downgraded" % path)
            else:
                self.installable.append({
                    'plugin': plugin,
                    'version': a.version,
                    'path': path
                })

        for path, version in installed.items():
            if path not in available:
                print "Plugin", path, "has been removed"
Esempio n. 12
0
def retrieve_plugins(interface, cached=True, cache={}):
    """
    Look up all plugins for a certain interface.

    If the plugin cache is enabled, this function will not attempt to reload
    plugins from disk or discover new plugins.

    :param interface interface: the interface to use
    :param bool cached: whether to use the in-memory plugin cache

    :returns: a dict of plugins, keyed by name
    :raises PluginException: no plugins could be found for the given interface
    """

    if cached and interface in cache:
        return cache[interface]

    log.msg("Discovering %s..." % interface)
    d = {}
    for p in getPlugins(interface, bravo.plugins):
        try:
            verifyObject(interface, p)
            log.msg(" ( ^^) Plugin: %s" % p.name)
            d[p.name] = p
        except BrokenImplementation, bi:
            if hasattr(p, "name"):
                log.msg(" ( ~~) Plugin %s is missing attribute %r!" %
                    (p.name, bi.name))
            else:
                log.msg(" ( >&) Plugin %s is unnamed and useless!" % p)
        except BrokenMethodImplementation, bmi:
            log.msg(" ( Oo) Plugin %s has a broken %s()!" % (p.name,
                bmi.method))
            log.err()
Esempio n. 13
0
            def check(cmd, mg):
                from twisted.plugin import getPlugins, IPlugin
                from twisted import plugins as twisted_plugins
                from mimic import plugins as mimic_plugins

                for plugin_package in [twisted_plugins, mimic_plugins]:
                    import time
                    list(getPlugins(IPlugin, package=plugin_package))

                import os
                def plugpath(what):
                    path_in_zip = what + "/plugins"
                    path_on_fs = (
                        os.path.abspath(
                            os.path.join(
                                os.path.dirname(
                                    __import__(what + ".plugins",
                                               fromlist=["nonempty"])
                                    .__file__),
                                "dropin.cache")
                        ))
                    os.utime(path_on_fs, (time.time() + 86400,) * 2)
                    return (path_in_zip, [path_on_fs])
                data_files = [plugpath("mimic"), plugpath("twisted")]

                return dict(loader_files=data_files)
Esempio n. 14
0
def retrieve_plugins(interface, cached=True, cache={}):
    """
    Look up all plugins for a certain interface.

    If the plugin cache is enabled, this function will not attempt to reload
    plugins from disk or discover new plugins.

    :param interface interface: the interface to use
    :param bool cached: whether to use the in-memory plugin cache

    :returns: a dict of plugins, keyed by name
    :raises PluginException: no plugins could be found for the given interface
    """

    if cached and interface in cache:
        return cache[interface]

    log.msg("Discovering %s..." % interface)
    d = {}
    for p in getPlugins(interface, bravo.plugins):
        try:
            verify_plugin(interface, p)
            d[p.name] = p
        except PluginException:
            pass

    if issubclass(interface, ISortedPlugin):
        # Sortable plugins need their edges mirrored.
        d = add_plugin_edges(d)

    cache[interface] = d
    return d
Esempio n. 15
0
    def test_detectNewFiles(self):
        """
        Check that L{plugin.getPlugins} is able to detect plugins added at
        runtime.
        """
        FilePath(__file__).sibling('plugin_extra1.py'
            ).copyTo(self.package.child('pluginextra.py'))
        try:
            # Check that the current situation is clean
            self.failIfIn('mypackage.pluginextra', sys.modules)
            self.failIf(hasattr(sys.modules['mypackage'], 'pluginextra'),
                        "mypackage still has pluginextra module")

            plgs = list(plugin.getPlugins(ITestPlugin, self.module))

            # We should find 2 plugins: the one in testplugin, and the one in
            # pluginextra
            self.assertEquals(len(plgs), 2)

            names = ['TestPlugin', 'FourthTestPlugin']
            for p in plgs:
                names.remove(p.__name__)
                p.test1()
        finally:
            self._unimportPythonModule(
                sys.modules['mypackage.pluginextra'],
                True)
Esempio n. 16
0
def iterate():
	import tj.plugins
	for module in plugin.getPlugins(IBotPlugin, tj.plugins):
		if(module.__module__ not in conf.get('active-plugins')):
			continue
		m = module()
		yield m
Esempio n. 17
0
 def subCommands(self):
     from twisted import plugin
     plugins = plugin.getPlugins(service.IServiceMaker)
     self.loadedPlugins = {}
     for plug in plugins:
         self.loadedPlugins[plug.tapname] = plug
         yield (plug.tapname, None, lambda: plug.options(), plug.description)
Esempio n. 18
0
def _put_plugin_resources(client_resource):
    # Plugin resources and plugin info
    load_list_css = []
    load_list_js = []
    mode_table = {}
    plugin_resources = Resource()
    client_resource.putChild('plugins', plugin_resources)
    for resource_def in getPlugins(IClientResourceDef, shinysdr.plugins):
        # Add the plugin's resource to static serving
        plugin_resources.putChild(resource_def.key, resource_def.resource)
        plugin_resource_url = '/client/plugins/' + urllib.quote(resource_def.key, safe='') + '/'
        # Tell the client to load the plugins
        # TODO constrain path values to be relative (not on a different origin, to not leak urls)
        if resource_def.load_css_path is not None:
            load_list_css.append(plugin_resource_url + resource_def.load_cs_path)
        if resource_def.load_js_path is not None:
            # TODO constrain value to be in the directory
            load_list_js.append(plugin_resource_url + resource_def.load_js_path)
    for mode_def in get_modes():
        mode_table[mode_def.mode] = {
            u'info_enum_row': mode_def.info.to_json(),
            u'can_transmit': mode_def.mod_class is not None
        }
    # Client gets info about plugins through this resource
    client_resource.putChild('plugin-index.json', static.Data(serialize({
        u'css': load_list_css,
        u'js': load_list_js,
        u'modes': mode_table,
    }).encode('utf-8'), 'application/json'))
Esempio n. 19
0
    def handlePlugins(self, info):
        """Give control to plugins.

        @param info: C{(proxy, equipment)} tuple
        """
        proxy, equipment = info
        proxy.version = 2       # Switch to version 2. Plugins should
                                # switch back to version 1 if needed.
        # Filter out plugins that do not handle our equipment
        plugins = [ plugin for plugin
                    in getPlugins(ICollector,
                                  wiremaps.collector.equipment)
                    if plugin.handleEquipment(str(equipment.oid)) ]
        if not plugins:
            print "No plugin found for OID %s, using generic one" % str(equipment.oid)
            plugins = [generic]
        print "Using %s to collect data from %s" % ([str(plugin.__class__)
                                                     for plugin in plugins],
                                                    proxy.ip)
        d = defer.succeed(None)
        # Run each plugin to complete C{equipment}
        for plugin in plugins:
            plugin.config = self.config
            d.addCallback(lambda x: plugin.collectData(equipment, proxy))
        # At the end, write C{equipment} to the database
        d.addCallback(lambda _: DatabaseWriter(equipment, self.config).write(self.dbpool))
        return d
Esempio n. 20
0
def _put_plugin_resources(wcommon, client_resource):
    """Plugin-defined resources and client-configuration."""
    load_list_css = []
    load_list_js = []
    mode_table = {}
    plugin_resources = Resource()
    client_resource.putChild('plugins', plugin_resources)
    for resource_def in getPlugins(_IClientResourceDef, shinysdr.plugins):
        # Add the plugin's resource to static serving
        plugin_resources.putChild(resource_def.key, resource_def.resource)
        plugin_resource_url = '/client/plugins/' + urllib.parse.quote(resource_def.key, safe='') + '/'
        # Tell the client to load the plugins
        # TODO constrain path values to be relative (not on a different origin, to not leak urls)
        if resource_def.load_css_path is not None:
            load_list_css.append(plugin_resource_url + resource_def.load_cs_path)
        if resource_def.load_js_path is not None:
            # TODO constrain value to be in the directory
            load_list_js.append(plugin_resource_url + resource_def.load_js_path)
    for mode_def in get_modes():
        mode_table[mode_def.mode] = {
            u'info_enum_row': mode_def.info.to_json(),
            u'can_transmit': mode_def.mod_class is not None
        }
    
    plugin_index = {
        'css': load_list_css,
        'js': load_list_js,
        'modes': mode_table,
    }
    client_resource.putChild('client-configuration', ClientConfigurationResource(wcommon, plugin_index))
Esempio n. 21
0
File: test.py Progetto: thomasvs/dad
    def _getProviders(self):
        from dad import plugins

        providers = {}
        for provider in plugin.getPlugins(idad.IPlayerProvider, plugins):
            providers[provider.name] = provider
        return providers
Esempio n. 22
0
def _scan_sites(env):
	"""
	Search for available site configuration objects.
	
	Register any found objects with the internal structures.
	"""
	global host_tree, debug_site_scan
	
	import modu.sites
	reload(modu.sites)
	
	plugins = plugin.getPlugins(ISite, modu.sites)
	
	for site_plugin in plugins:
		if(debug_site_scan):
			env['wsgi.errors'].write('Found %r\n' % (site_plugin,))
		site = site_plugin()
		app = Application(site)
		
		root = app.tree.get_data_at('/')
		webroot = os.path.join(app.approot, app.webroot)
		app.tree.register('/', (static.FileResource, (webroot, root), {}), clobber=True)
		
		domain = app.base_domain
		if(domain.find(':') == -1):
			domain += ':' + env['SERVER_PORT']
		
		host_node = host_tree.setdefault(domain, url.URLNode())
		base_path = app.base_path
		if not(base_path):
			base_path = '/'
		
		if(debug_site_scan):
			env['wsgi.errors'].write('Loaded %r for %r\n' % (site_plugin, domain))
		host_node.register(base_path, app, clobber=True)
Esempio n. 23
0
    def __init__(self, config):
        self.channels = config['channels']
        self.nickname = config['nickname']
        self.history = {}

        self.loader = PluginLoader()
        self.loader.config = config

        if 'db' in config:
            print('Loading db from config: ' + config['db'])
            db_engine = sqlalchemy.create_engine(config['db'])
        else:
            print('Using in-memory db')
            db_engine = sqlalchemy.create_engine('sqlite:///:memory:')
        DBSession = orm.sessionmaker(db_engine)
        session = DBSession()

        self.loader.db = DB(db_engine, session)

        # Load all plugins mentioned in the configuration. Allow globbing.
        config_matches = set()
        for plugin in getPlugins(BaseInterface, package=plugins):
            for pattern in config['plugins']:
                if fnmatch(plugin.name, pattern):
                    self.loader.registerPlugin(plugin)
                    config_matches.add(pattern)
                    break
        for pattern in config['plugins']:
            if pattern not in config_matches:
                log.warning('No plugin matched pattern "%s"', pattern)
Esempio n. 24
0
File: cli.py Progetto: CMB/hamper
    def __init__(self, config):
        self.loader = PluginLoader()
        self.loader.config = config

        self.history = {}


        if 'db' in config:
            print('Loading db from config: ' + config['db'])
            db_engine = sqlalchemy.create_engine(config['db'])
        else:
            print('Using in-memory db')
            db_engine = sqlalchemy.create_engine('sqlite:///:memory:')
        DBSession = orm.sessionmaker(db_engine)
        session = DBSession()

        self.loader.db = DB(db_engine, session)

        # Load all plugins mentioned in the configuration. Allow globbing.
        print "Loading plugins", config["plugins"]
        plugins = getPlugins(BaseInterface, package=hamper.plugins)
        for plugin in plugins:
            for pattern in config["plugins"]:
                if fnmatch(plugin.name, pattern):
                    self.loader.registerPlugin(plugin)
Esempio n. 25
0
 def _testPlugins(self):
     plugins = list(plugin.getPlugins(plugin.ITestPlugin2))
     self.assertEquals(len(plugins), 2)
     names = ['AnotherTestPlugin', 'ThirdTestPlugin']
     for p in plugins:
         names.remove(p.__name__)
         p.test()
Esempio n. 26
0
def loadApps():
    """
    Read the IResource plugins
    """
    import goonsite.plugins
    plugins = getPlugins(IAppFactory, goonsite.plugins)
    return dict([(p.name, p) for p in plugins])
Esempio n. 27
0
 def loadModule(self, name):
     for module in getPlugins(IBotModule, heufybot.modules):
         if module.name and module.name.lower() == name.lower():
             rebuild(importlib.import_module(module.__module__))
             self._loadModuleData(module)
             return module.name
     raise ModuleLoaderError(name, "The module could not be found.", ModuleLoadType.LOAD)
Esempio n. 28
0
 def test_findCheckerFactories(self):
     """
     Test that findCheckerFactories returns all available plugins.
     """
     availablePlugins = list(strcred.findCheckerFactories())
     for plg in plugin.getPlugins(strcred.ICheckerFactory):
         self.assertIn(plg, availablePlugins)
Esempio n. 29
0
    def __init__(self, config):
        self.channels = config['channels']
        self.nickname = config['nickname']
        self.config = config

        self.history = {}
        self.plugins = {
            'base_plugin': [],
            'presence': [],
            'chat': [],
            'population': [],
        }

        if 'db' in config:
            print('Loading db from config: ' + config['db'])
            self.db_engine = sqlalchemy.create_engine(config['db'])
        else:
            print('Using in-memory db')
            self.db_engine = sqlalchemy.create_engine('sqlite:///:memory:')
        DBSession = orm.sessionmaker(self.db_engine)
        self.db = DBSession()

        # Load all plugins mentioned in the configuration. Allow globbing.
        for plugin in getPlugins(BaseInterface, package=plugins):
            self.registerPlugin(plugin)
Esempio n. 30
0
 def loadModule(self, name):
     for module in getPlugins(IBotModule, heufybot.modules):
         if not module.name:
             raise ModuleLoaderError("???", "Module did not provide a name")
         if module.name == name:
             rebuild(importlib.import_module(module.__module__))
             self._loadModuleData(module)
             break
Esempio n. 31
0
                 "Programming Language :: Python :: Implementation :: PyPy",
                 "Topic :: Internet",
                 "Topic :: Internet :: WWW/HTTP",
                 "Topic :: Communications",
                 "Topic :: System :: Distributed Computing",
                 "Topic :: Software Development :: Libraries",
                 "Topic :: Software Development :: Libraries :: Python Modules",
                 "Topic :: Software Development :: Object Brokering"],
    keywords='autobahn crossbar websocket realtime rfc6455 wamp rpc pubsub twisted asyncio xbr data-markets blockchain ethereum'
)


# regenerate Twisted plugin cache
try:
    from twisted.internet import reactor
    print("Twisted found (default reactor is {0})".format(reactor.__class__))
except ImportError:
    # the user doesn't have Twisted, so skip
    pass
else:
    # Make Twisted regenerate the dropin.cache, if possible. This is necessary
    # because in a site-wide install, dropin.cache cannot be rewritten by
    # normal users.
    try:
        from twisted.plugin import IPlugin, getPlugins
        list(getPlugins(IPlugin))
    except Exception as e:
        print("Failed to update Twisted plugin cache: {0}".format(e))
    else:
        print("Twisted dropin.cache regenerated.")
Esempio n. 32
0
def clientFromString(reactor, description):
    """
    Construct a client endpoint from a description string.

    Client description strings are much like server description strings,
    although they take all of their arguments as keywords, aside from host and
    port.

    You can create a TCP client endpoint with the 'host' and 'port' arguments,
    like so::

        clientFromString(reactor, "tcp:host=www.example.com:port=80")

    or, without specifying host and port keywords::

        clientFromString(reactor, "tcp:www.example.com:80")

    Or you can specify only one or the other, as in the following 2 examples::

        clientFromString(reactor, "tcp:host=www.example.com:80")
        clientFromString(reactor, "tcp:www.example.com:port=80")

    or an SSL client endpoint with those arguments, plus the arguments used by
    the server SSL, for a client certificate::

        clientFromString(reactor, "ssl:web.example.com:443:"
                                  "privateKey=foo.pem:certKey=foo.pem")

    to specify your certificate trust roots, you can identify a directory with
    PEM files in it with the C{caCertsDir} argument::

        clientFromString(reactor, "ssl:host=web.example.com:port=443:"
                                  "caCertsDir=/etc/ssl/certs")

    You can create a UNIX client endpoint with the 'path' argument and optional
    'lockfile' and 'timeout' arguments::

        clientFromString(reactor, "unix:path=/var/foo/bar:lockfile=1:timeout=9")

    or, with the path as a positional argument with or without optional
    arguments as in the following 2 examples::

        clientFromString(reactor, "unix:/var/foo/bar")
        clientFromString(reactor, "unix:/var/foo/bar:lockfile=1:timeout=9")

    This function is also extensible; new endpoint types may be registered as
    L{IStreamClientEndpointStringParser} plugins.  See that interface for more
    information.

    @param reactor: The client endpoint will be constructed with this reactor.

    @param description: The strports description to parse.

    @return: A new endpoint which can be used to connect with the parameters
        given by by C{description}.
    @rtype: L{IStreamClientEndpoint<twisted.internet.interfaces.IStreamClientEndpoint>}

    @since: 10.2
    """
    args, kwargs = _parse(description)
    aname = args.pop(0)
    name = aname.upper()
    for plugin in getPlugins(IStreamClientEndpointStringParser):
        if plugin.prefix.upper() == name:
            return plugin.parseStreamClient(*args, **kwargs)
    if name not in _clientParsers:
        raise ValueError("Unknown endpoint type: %r" % (aname, ))
    kwargs = _clientParsers[name](*args, **kwargs)
    return _endpointClientFactories[name](reactor, **kwargs)
Esempio n. 33
0
def refresh_plugin_cache():
    from twisted.plugin import IPlugin, getPlugins
    list(getPlugins(IPlugin))
Esempio n. 34
0
 def __init__(self):
     self.__all_modes = {d.mode: d
         for d in getPlugins(IModeDef, plugins)}
     self.__available_modes = {d.mode: d
          for d in self.__all_modes.itervalues()
          if d.available}
Esempio n. 35
0
def _zshReporterAction():
    return "(%s)" % (" ".join(
        [p.longOpt for p in plugin.getPlugins(itrial.IReporter)]), )
Esempio n. 36
0
from shinysdr.db_import import GeoFilter, IImporter, _IImporterDef
from shinysdr import plugins


def _general_warning_callback(msg):
    print >>sys.stderr, msg


def _add_file_wrapper(importer, filename, open_file):
    def warning_callback(msg):
        print >>sys.stderr, u'%s:%s' % (filename, msg)
    
    importer.add_file(filename, open_file, warning_callback)


_importer_defs = {p.name: p for p in getPlugins(_IImporterDef, plugins) if p.available}


def _importer_list_msg():
    out = 'Known importers:\n'
    for name, idef in _importer_defs.iteritems():
        out += '  %s: %s\n' % (name, idef.description)
    return out


def _parse_args(argv):
    parser = argparse.ArgumentParser(
        prog=argv[0],
        epilog=_importer_list_msg(),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('importer_name', metavar='IMPORTER',
Esempio n. 37
0
def findCheckerFactories():
    """
    Find all objects that implement L{ICheckerFactory}.
    """
    return getPlugins(ICheckerFactory)
Esempio n. 38
0
 def fromPlugins(cls, clock):
     """
     Create a :obj:`MimicCore` from all :obj:`IAPIMock` plugins.
     """
     return cls(clock, list(getPlugins(IAPIMock, plugins)))
Esempio n. 39
0
 def __init__(self):
     self.__modes = {p.mode: p for p in getPlugins(_IModeDef, plugins) if p.available}
Esempio n. 40
0
def getReactorTypes() -> Iterable[IReactorInstaller]:
    """
    Return an iterator of L{IReactorInstaller} plugins.
    """
    return getPlugins(IReactorInstaller)
Esempio n. 41
0

def _general_warning_callback(msg):
    print >> sys.stderr, msg


def _add_file_wrapper(importer, filename, open_file):
    def warning_callback(msg):
        print >> sys.stderr, u'%s:%s' % (filename, msg)

    importer.add_file(filename, open_file, warning_callback)


_importer_defs = {
    p.name: p
    for p in getPlugins(_IImporterDef, plugins) if p.available
}


def _importer_list_msg():
    out = 'Known importers:\n'
    for name, idef in _importer_defs.iteritems():
        out += '  %s: %s\n' % (name, idef.description)
    return out


def _parse_args(argv):
    parser = argparse.ArgumentParser(
        prog=argv[0],
        epilog=_importer_list_msg(),
        formatter_class=argparse.RawDescriptionHelpFormatter)
Esempio n. 42
0
def _reporterAction():
    return usage.CompleteList(
        [p.longOpt for p in plugin.getPlugins(itrial.IReporter)])
Esempio n. 43
0
 def execute(self, server, source, command, params, data):
     if command == "addalias":
         if len(params) < 2:
             self.replyPRIVMSG(server, source, "Add which alias?")
             return
         alias = params[0].lower()
         if alias in self.aliases:
             self.replyPRIVMSG(
                 server, source,
                 "{!r} already exists as an alias.".format(alias))
             return
         commandsList = []
         for module in getPlugins(IBotModule, heufybot.modules):
             if isinstance(module, BotCommand):
                 commandsList += module.triggers()
         if alias in commandsList:
             self.replyPRIVMSG(
                 server, source,
                 "{!r} already exists as a command.".format(alias))
             return
         if params[1] not in commandsList:
             self.replyPRIVMSG(
                 server, source,
                 "{!r} is not a valid command or alias.".format(params[1]))
             return
         replacement = " ".join(params[1:])
         self.aliases[alias] = {
             "replacement": replacement,
             "helptext": None
         }
         self.commandHelp[alias] = self._getAliasReplacementMessage(alias)
         self._syncAliases()
         self.replyPRIVMSG(
             server, source,
             "{!r} has been added as an alias for {!r}.".format(
                 alias, replacement))
     elif command == "delalias":
         if len(params) < 1:
             self.replyPRIVMSG(server, source, "Remove which alias?")
             return
         alias = params[0].lower()
         if self._checkAliasExists(alias, server, source):
             del self.aliases[alias]
             if alias in self.commandHelp:
                 del self.commandHelp[alias]
             self._syncAliases()
             self.replyPRIVMSG(server, source,
                               "Alias {!r} has been removed.".format(alias))
     elif command == "listaliases":
         if len(self.aliases) == 0:
             self.replyPRIVMSG(server, source,
                               "No aliases have been configured.")
         else:
             self.replyPRIVMSG(
                 server, source, "Aliases: {}".format(". ".join(
                     sorted(self.aliases.keys()))))
     elif command == "showalias":
         if len(params) < 1:
             self.replyPRIVMSG(server, source, "Add help for which alias?")
             return
         alias = params[0].lower()
         if self._checkAliasExists(alias, server, source):
             self.replyPRIVMSG(server, source,
                               self._getAliasReplacementMessage(alias))
     elif command == "setaliashelp":
         if len(params) < 2:
             self.replyPRIVMSG(server, source, "Add help to which alias?")
             return
         alias = params[0].lower()
         if self._checkAliasExists(alias, server, source):
             helpText = " ".join(params[1:])
             self.aliases[alias]["helptext"] = helpText
             self.commandHelp[alias] = helpText
             self._syncAliases()
             self.replyPRIVMSG(
                 server, source,
                 "Help text for {!r} has been set to {!r}.".format(
                     alias, helpText))
     else:
         src = data["channel"] if "channel" in data else data["user"]
         message = self._getAliasedMessage(server, src, data["user"],
                                           command, params)
         if message:
             if "channel" in data:
                 self.bot.moduleHandler.runGenericAction(
                     "message-channel", server, src, data["user"], message)
             else:
                 self.bot.moduleHandler.runGenericAction(
                     "message-user", server, src, message)
Esempio n. 44
0
 def _collect_storage_plugins(cls, storage_plugin_names):
     """
     Get the storage plugins with names matching those given.
     """
     return list(plugin for plugin in getPlugins(IFoolscapStoragePlugin)
                 if plugin.name in storage_plugin_names)