File: package_plugin_manager.py

package info (click to toggle)
python-envisage 7.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,880 kB
  • sloc: python: 8,696; makefile: 76; sh: 5
file content (161 lines) | stat: -rw-r--r-- 5,655 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# (C) Copyright 2007-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
""" A plugin manager that finds plugins in packages on the 'plugin_path'. """


import logging
import sys
import warnings

from apptools.io import File
from traits.api import Directory, List, on_trait_change

from .plugin_manager import PluginManager

logger = logging.getLogger(__name__)


class PackagePluginManager(PluginManager):
    """A plugin manager that finds plugins in packages on the 'plugin_path'.

    All items in 'plugin_path' are directory names and they are all added to
    'sys.path' (if not already present). Each directory is then searched for
    plugins as follows:-

    a) If the package contains a 'plugins.py' module, then we import it and
    look for a callable 'get_plugins' that takes no arguments and returns
    a list of plugins (i.e. instances that implement 'IPlugin'!).

    b) If the package contains any modules named in the form 'xxx_plugin.py'
    then the module is imported and if it contains a callable 'XXXPlugin' it is
    called with no arguments and it must return a single plugin.

    """

    def __init__(self, **traits):
        warnings.warn(
            (
                "The PackagePluginManager is deprecated. The recommended "
                "approach is to install plugin-containing packages into "
                "site-packages and advertise the plugins via entry points. "
            ),
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(**traits)

    # Plugin manifest.
    PLUGIN_MANIFEST = "plugins.py"

    #### 'PackagePluginManager' protocol ######################################

    # A list of directories that will be searched to find plugins.
    plugin_path = List(Directory)

    @on_trait_change("plugin_path[]")
    def _update_path_and_reset_plugins(self, obj, trait_name, removed, added):
        self._update_sys_dot_path(removed, added)
        self.reset_traits(["_plugins"])

    #### Protected 'PluginManager' protocol ###################################

    def __plugins_default(self):
        """Trait initializer."""

        plugins = [
            plugin
            for plugin in self._harvest_plugins_in_packages()
            if self._include_plugin(plugin.id)
        ]

        logger.debug("package plugin manager found plugins <%s>", plugins)

        return plugins

    #### Private protocol #####################################################

    def _get_plugins_module(self, package_name):
        """Import 'plugins.py' from the package with the given name.

        If the package does not exist, or does not contain 'plugins.py' then
        return None.

        """

        try:
            module = __import__(
                package_name + ".plugins", fromlist=["plugins"]
            )

        except ImportError:
            module = None

        return module

    # smell: Looooong and ugly!
    def _harvest_plugins_in_package(self, package_name, package_dirname):
        """Harvest plugins found in the given package."""

        # If the package contains a 'plugins.py' module, then we import it and
        # look for a callable 'get_plugins' that takes no arguments and returns
        # a list of plugins (i.e. instances that implement 'IPlugin'!).
        plugins_module = self._get_plugins_module(package_name)
        if plugins_module is not None:
            factory = getattr(plugins_module, "get_plugins", None)
            if factory is not None:
                plugins = factory()

        # Otherwise, look for any modules in the form 'xxx_plugin.py' and
        # see if they contain a callable in the form 'XXXPlugin' and if they
        # do, call it with no arguments to get a plugin!
        else:
            plugins = []
            logger.debug("Looking for plugins in %s" % package_dirname)
            for child in File(package_dirname).children or []:
                if child.ext == ".py" and child.name.endswith("_plugin"):
                    module = __import__(
                        package_name + "." + child.name, fromlist=[child.name]
                    )

                    atoms = child.name.split("_")
                    capitalized = [atom.capitalize() for atom in atoms]
                    factory_name = "".join(capitalized)

                    factory = getattr(module, factory_name, None)
                    if factory is not None:
                        plugins.append(factory())

        return plugins

    def _harvest_plugins_in_packages(self):
        """Harvest plugins found in packages on the plugin path."""

        plugins = []
        for dirname in self.plugin_path:
            for child in File(dirname).children or []:
                if child.is_package:
                    plugins.extend(
                        self._harvest_plugins_in_package(
                            child.name, child.path
                        )
                    )

        return plugins

    def _update_sys_dot_path(self, removed, added):
        """Add/remove the given entries from sys.path."""

        for dirname in removed:
            if dirname in sys.path:
                sys.path.remove(dirname)

        for dirname in added:
            if dirname not in sys.path:
                sys.path.append(dirname)