├── .codeclimate.yml
├── .coveragerc
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── LICENSE.md
├── README.rst
├── docs
├── Makefile
└── source
│ ├── conf.py
│ └── index.rst
├── pluginmanager
├── __init__.py
├── compat.py
├── directory_manager.py
├── entry_point_manager.py
├── file_filters
│ ├── __init__.py
│ ├── _forbidden_name.py
│ ├── filenames.py
│ ├── matching_regex.py
│ └── with_info_file.py
├── file_manager.py
├── iplugin.py
├── module_filters
│ ├── __init__.py
│ ├── keyword_parser.py
│ └── subclass_parser.py
├── module_manager.py
├── plugin_filters
│ ├── __init__.py
│ ├── active.py
│ └── by_name.py
├── plugin_interface.py
├── plugin_manager.py
└── util.py
├── requirements-dev.txt
├── setup.cfg
├── setup.py
└── tests
├── __init__.py
├── compat.py
├── test_directory_manager.py
├── test_entry_point_manager.py
├── test_file_filters
├── __init__.py
├── test_filenames.py
├── test_matching_regex.py
└── test_with_info_file.py
├── test_file_manager.py
├── test_filter_integration.py
├── test_iplugin.py
├── test_module_filters
├── __init__.py
├── test_keyword_parser.py
└── test_subclass_parser.py
├── test_module_manager.py
├── test_plugin_filters
├── __init__.py
├── test_active.py
└── test_by_name.py
├── test_plugin_interface.py
├── test_plugin_manager.py
└── test_util.py
/.codeclimate.yml:
--------------------------------------------------------------------------------
1 | languages:
2 | Python: true
3 |
4 | exclude_paths:
5 | - 'tests/*'
6 |
--------------------------------------------------------------------------------
/.coveragerc:
--------------------------------------------------------------------------------
1 | [run]
2 | omit = */tests/*, */distutils/*, /tmp/*, */site-packages/*
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.py[cod]
2 | *.swp
3 | __pycache__
4 | .coverage
5 | .installed.cfg
6 | .mr.developer.cfg
7 | bin/
8 | plugins/
9 | db/*
10 | log/*
11 | env/
12 | dist/
13 | build/
14 | *.egg-info/
15 | .idea/
16 | develop-eggs/
17 | src/
18 | doc/src
19 | _html/
20 | eggs/
21 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 |
3 | notifications:
4 | email: false
5 |
6 | python:
7 | - "2.7"
8 | - "3.3"
9 | - "3.4"
10 | - "3.5"
11 | - "3.6"
12 | - "pypy"
13 | - "pypy3"
14 |
15 | matrix:
16 | include:
17 | - os: linux
18 | python: 3.5
19 | env: TEST_MODE='doctest'
20 |
21 | allow_failures:
22 | - env: TEST_MODE='doctest'
23 |
24 | # command to install dependencies
25 | install:
26 | - pip install flake8
27 | - if [[ $TEST_MODE == 'doctest' ]]; then pip install sphinx; fi
28 | - pip install coverage
29 | - pip install python-coveralls
30 |
31 | # command to run tests
32 | script:
33 | - coverage run -m unittest discover
34 | - flake8 pluginmanager
35 | - flake8 tests
36 | - if [[ $TEST_MODE == 'doctest' ]]; then make -C docs doctest; fi
37 |
38 | after_success:
39 | - coverage report
40 | - coveralls
41 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change Log
2 | All notable changes to this project will be documented in this file.
3 | This project adheres to [Semantic Versioning](http://semver.org/).
4 |
5 | ## [Unreleased]
6 | - Nothing!
7 |
8 | ## [0.3.2]
9 | ### Added
10 | - Entry Point Manager!
11 | - Class documentation for PluginInterface
12 |
13 | ## [0.3.1]
14 | ### Added
15 | - Method documentation to PluginInterface
16 | - `except_blacklisted` method argument to add/set plugin filepaths methods in PluginInterface. This argument was present in the underlying method call, but had not been implemented in PluginInterface yet.
17 | - `remove_from_stored` method argument to the add/set blacklisted filepaths in PluginInterface. This argument was again, present in the underlying method call, but had not been implemented in PluginInterface.
18 |
19 | ### Changed
20 | - Removed `auto_manage_state` variable from PluginInterface initialization. The method call `collect_plugins` now has a `store_collected_plugins` boolean argument which tells the class whether to make the PluginInterface instance track the plugins state or not. Default is `True`.
21 | - Method argument for PluginInterface.get_file_filters from `file_function` to `filter_function`.
22 | - FileManager changes all paths to absolute paths in method calls involving filepaths.
23 | - Method documentation in FileManager, DirectoryManager, PluginManager
24 |
25 | ### Fixed
26 | - Previous wheel packages accidently included tests. Moved tests to the project root and fixed setup.py to not include tests and also automatically remove the egg package to ensure that no previous state gets bundled in the wheel packages.
27 |
28 | ## [0.3.0]
29 | ### Added
30 | - Method documentation for `ModuleManager` and `PluginManager`
31 | - `plugins` and `blacklisted_plugins` arguments to `PluginManager` initialization call.
32 | - checks to make sure that plugins have `activate` methods before trying to call the `activate` method using the `activate_plugins` method in `PluginManager`
33 |
34 | ### Changed
35 | - `module_filters` to be `module_plugin_filters` in `ModuleManager` and `PluginInterface`. This is a API change which affects the method calls in both classes.
36 | - Moved `PLUGIN_FORBIDDEN_NAME` from the init file in file_filters to being defined in it's own file. The linter was throwing a hissy fit about it being defined in the init file.
37 |
38 | ### Removed
39 | - `except_blacklisted` method argument from `add_site_packages_paths` in `DirectoryManager`. If the site packages path is blacklisted, shouldn't use this method.
40 |
41 | ## [0.2.2]
42 | ### Added
43 | - Method documentaiton for `ModuleManager`
44 |
45 | ### Changed
46 | - `ModuleManager` no longer has support for blacklisted filepaths. This was not used by the default implementation in `PluginInterface` as `FileManager` handles the blacklisting for the package. Initializer call no longer allows a `blacklisted_filepaths` option and the blacklist methods were removed.
47 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | ==========================
3 | Version 3, 29 June 2007
4 | ==========================
5 |
6 | > Copyright (C) 2007 Free Software Foundation, Inc.
7 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
8 |
9 | # Preamble
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | # TERMS AND CONDITIONS
72 |
73 | ## 0. Definitions.
74 |
75 | _"This License"_ refers to version 3 of the GNU General Public License.
76 |
77 | _"Copyright"_ also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | _"The Program"_ refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as _"you"_. _"Licensees"_ and
82 | "recipients" may be individuals or organizations.
83 |
84 | To _"modify"_ a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a _"modified version"_ of the
87 | earlier work or a work _"based on"_ the earlier work.
88 |
89 | A _"covered work"_ means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To _"propagate"_ a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To _"convey"_ a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | ## 1. Source Code.
113 |
114 | The _"source code"_ for a work means the preferred form of the work
115 | for making modifications to it. _"Object code"_ means any non-source
116 | form of a work.
117 |
118 | A _"Standard Interface"_ means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The _"System Libraries"_ of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The _"Corresponding Source"_ for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | ## 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | ## 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | ## 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | ## 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | ## 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A _"User Product"_ is either (1) a _"consumer product"_, which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | _"Installation Information"_ for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | ## 7. Additional Terms.
344 |
345 | _"Additional permissions"_ are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | ## 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | ## 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | ## 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An _"entity transaction"_ is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | ## 11. Patents.
472 |
473 | A _"contributor"_ is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's _"essential patent claims"_ are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | ## 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | ## 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | ## 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | ## 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | ## 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | ## 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | # END OF TERMS AND CONDITIONS
622 | --------------------------------------------------------------------------
623 |
624 |
625 | # How to Apply These Terms to Your New Programs
626 |
627 | If you develop a new program, and you want it to be of the greatest
628 | possible use to the public, the best way to achieve this is to make it
629 | free software which everyone can redistribute and change under these terms.
630 |
631 | To do so, attach the following notices to the program. It is safest
632 | to attach them to the start of each source file to most effectively
633 | state the exclusion of warranty; and each file should have at least
634 | the "copyright" line and a pointer to where the full notice is found.
635 |
636 |
637 | Copyright (C)
638 |
639 | This program is free software: you can redistribute it and/or modify
640 | it under the terms of the GNU General Public License as published by
641 | the Free Software Foundation, either version 3 of the License, or
642 | (at your option) any later version.
643 |
644 | This program is distributed in the hope that it will be useful,
645 | but WITHOUT ANY WARRANTY; without even the implied warranty of
646 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
647 | GNU General Public License for more details.
648 |
649 | You should have received a copy of the GNU General Public License
650 | along with this program. If not, see .
651 |
652 | Also add information on how to contact you by electronic and paper mail.
653 |
654 | If the program does terminal interaction, make it output a short
655 | notice like this when it starts in an interactive mode:
656 |
657 | Copyright (C)
658 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
659 | This is free software, and you are welcome to redistribute it
660 | under certain conditions; type 'show c' for details.
661 |
662 | The hypothetical commands _'show w'_ and _'show c'_ should show the appropriate
663 | parts of the General Public License. Of course, your program's commands
664 | might be different; for a GUI interface, you would use an "about box".
665 |
666 | You should also get your employer (if you work as a programmer) or school,
667 | if any, to sign a "copyright disclaimer" for the program, if necessary.
668 | For more information on this, and how to apply and follow the GNU GPL, see
669 | .
670 |
671 | The GNU General Public License does not permit incorporating your program
672 | into proprietary programs. If your program is a subroutine library, you
673 | may consider it more useful to permit linking proprietary applications with
674 | the library. If this is what you want to do, use the GNU Lesser General
675 | Public License instead of this License. But first, please read
676 | .
677 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | .. pluginmanager documentation master file, created by
2 | sphinx-quickstart on Wed Dec 9 22:32:56 2015.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | .. testsetup:: quickstart
7 |
8 | import os
9 | from pluginmanager.tests.compat import tempfile
10 | tempdirectory = tempfile.TemporaryDirectory()
11 | plugin_directory_path = tempdirectory.name
12 | path = os.path.join(tempdirectory.name, 'test.py')
13 | with open(path, 'w+') as f:
14 | f.write('from pluginmanager import IPlugin\nclass Test(IPlugin):\n pass')
15 |
16 | pluginmanager
17 | =============
18 | |Build Status| |Coverage Status| |Code Climate|
19 |
20 | python plugin management, simplified.
21 |
22 |
23 | `Documentation `_
24 |
25 | `Source Code `_
26 |
27 | Library under development. Contains rough edges/unfinished functionality. API subject to changes.
28 |
29 | Installation
30 | ------------
31 |
32 | ::
33 |
34 | pip install pluginmanager
35 |
36 | -or- ::
37 |
38 | pip install git+https://github.com/benhoff/pluginmanager.git
39 |
40 | Quickstart
41 | ----------
42 |
43 | ::
44 |
45 | from pluginmanager import PluginInterface
46 |
47 | plugin_interface = PluginInterface()
48 | plugin_interface.set_plugin_directories(plugin_directory_path)
49 | plugin_interface.collect_plugins()
50 |
51 | plugins = plugin_interface.get_instances()
52 |
53 |
54 | Custom Plugins
55 | --------------
56 |
57 | The quickstart will only work if you subclass `IPlugin` for your custom plugins.
58 |
59 | ::
60 |
61 | import pluginmanager
62 |
63 | class MyCustomPlugin(pluginmanager.IPlugin):
64 | def __init__(self):
65 | self.name = 'custom_name'
66 | super().__init__()
67 |
68 | Or register your class as subclass of IPlugin.
69 |
70 | ::
71 |
72 | import pluginmanager
73 |
74 | pluginmanager.IPlugin.register(YourClassHere)
75 |
76 | Add Plugins Manually
77 | --------------------
78 | Add classes.
79 |
80 | ::
81 |
82 | import pluginmanager
83 |
84 | class CustomClass(pluginmanager.IPlugin):
85 | pass
86 |
87 | plugin_interface = pluginmanager.PluginInterface()
88 | plugin_interface.add_plugins(CustomClass)
89 |
90 | plugins = plugin_interface.get_instances()
91 |
92 |
93 | Alternatively, add instances.
94 |
95 | ::
96 |
97 | import pluginmanager
98 |
99 | class CustomClass(pluginmanager.IPlugin):
100 | pass
101 |
102 | custom_class_instance = CustomClass()
103 |
104 | plugin_interface = pluginmanager.PluginInterface()
105 | plugin_interface.add_plugins(custom_class_instance)
106 |
107 | plugins = plugin_interface.get_instances()
108 |
109 |
110 | pluginmanager is defaulted to automatically instantiate unique instances. Disable automatic instantiation.
111 |
112 | ::
113 |
114 | import pluginmanager
115 |
116 | plugin_interface = pluginmanager.PluginInterface()
117 | plugin_manager = plugin_interface.plugin_manager
118 |
119 | plugin_manager.instantiate_classes = False
120 |
121 | Disable uniqueness (Only one instance of class per pluginmanager)
122 |
123 | ::
124 |
125 | import pluginmanager
126 |
127 | plugin_interface = pluginmanager.PluginInterface()
128 | plugin_manager = plugin_interface.plugin_manager
129 |
130 | plugin_manager.unique_instances = False
131 |
132 | Filter Instances
133 | ----------------
134 |
135 | Pass in a class to get back just the instances of a class
136 |
137 | ::
138 |
139 | import pluginmanager
140 |
141 | class MyPluginClass(pluginmanager.IPlugin):
142 | pass
143 |
144 | plugin_interface = pluginmanager.PluginInterface()
145 | plugin_interface.add_plugins(MyPluginClass)
146 |
147 | all_instances_of_class = plugin_interface.get_instances(MyPluginClass)
148 |
149 |
150 | Alternatively, create and pass in your own custom filters. Either make a class based filter
151 |
152 | ::
153 |
154 | # create a custom plugin class
155 | class Plugin(pluginmanager.IPlugin):
156 | def __init__(self, name):
157 | self.name = name
158 |
159 | # create a custom filter
160 | class NameFilter(object):
161 | def __init__(self, name):
162 | self.stored_name = name
163 |
164 | def __call__(self, plugins):
165 | result = []
166 | for plugin in plugins:
167 | if plugin.name == self.stored_name:
168 | result.append(plugin)
169 | return result
170 |
171 | # create an instance of our custom filter
172 | mypluginclass_name_filter = NameFilter('good plugin')
173 |
174 | plugin_interface = pluginmanager.PluginInterface()
175 | plugin_interface.add_plugins([Plugin('good plugin'),
176 | Plugin('bad plugin')])
177 |
178 | filtered_plugins = plugin_interface.get_instances(mypluginclass_name_filter)
179 |
180 |
181 | Or make a function based filter
182 |
183 | ::
184 |
185 | # create a custom plugin class
186 | class Plugin(pluginmanager.IPlugin):
187 | def __init__(self, name):
188 | self.name = name
189 |
190 | # create a function based filter
191 | def custom_filter(plugins):
192 | result = []
193 | for plugin in plugins:
194 | if plugin.name == 'good plugin':
195 | result.append(plugin)
196 | return result
197 |
198 | plugin_interface = pluginmanager.PluginInterface()
199 | plugin_interface.add_plugins([Plugin('good plugin'),
200 | Plugin('bad plugin')])
201 |
202 | filtered_plugins = plugin_interface.get_instances(mypluginclass_name_filter)
203 |
204 |
205 | Class Overview
206 | --------------
207 |
208 | .. currentmodule:: pluginmanager
209 | .. autosummary::
210 | :toctree: stubs
211 |
212 | DirectoryManager
213 | FileManager
214 | ModuleManager
215 | PluginManager
216 | PluginInterface
217 |
218 |
219 | Indices and tables
220 | ==================
221 |
222 | * :ref:`genindex`
223 | * :ref:`modindex`
224 | * :ref:`search`
225 |
226 | .. |Build Status| image:: https://travis-ci.org/benhoff/pluginmanager.svg?branch=master
227 | :target: https://travis-ci.org/benhoff/pluginmanager
228 | .. |Coverage Status| image:: https://coveralls.io/repos/benhoff/pluginmanager/badge.svg?branch=master&service=github
229 | :target: https://coveralls.io/github/benhoff/pluginmanager?branch=master
230 | .. |Code Climate| image:: https://codeclimate.com/github/benhoff/pluginmanager/badges/gpa.svg
231 | :target: https://codeclimate.com/github/benhoff/pluginmanager
232 |
233 |
234 |
235 | .. testcleanup::
236 | tempdirectory.cleanup()
237 |
238 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = build
9 |
10 | # User-friendly check for sphinx-build
11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
13 | endif
14 |
15 | # Internal variables.
16 | PAPEROPT_a4 = -D latex_paper_size=a4
17 | PAPEROPT_letter = -D latex_paper_size=letter
18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
19 | # the i18n builder cannot share the environment and doctrees with the others
20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
21 |
22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext
23 |
24 | help:
25 | @echo "Please use \`make ' where is one of"
26 | @echo " html to make standalone HTML files"
27 | @echo " dirhtml to make HTML files named index.html in directories"
28 | @echo " singlehtml to make a single large HTML file"
29 | @echo " pickle to make pickle files"
30 | @echo " json to make JSON files"
31 | @echo " htmlhelp to make HTML files and a HTML help project"
32 | @echo " qthelp to make HTML files and a qthelp project"
33 | @echo " applehelp to make an Apple Help Book"
34 | @echo " devhelp to make HTML files and a Devhelp project"
35 | @echo " epub to make an epub"
36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
37 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
39 | @echo " text to make text files"
40 | @echo " man to make manual pages"
41 | @echo " texinfo to make Texinfo files"
42 | @echo " info to make Texinfo files and run them through makeinfo"
43 | @echo " gettext to make PO message catalogs"
44 | @echo " changes to make an overview of all changed/added/deprecated items"
45 | @echo " xml to make Docutils-native XML files"
46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes"
47 | @echo " linkcheck to check all external links for integrity"
48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
49 | @echo " coverage to run coverage check of the documentation (if enabled)"
50 |
51 | clean:
52 | rm -rf $(BUILDDIR)/*
53 |
54 | html:
55 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
56 | @echo
57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
58 |
59 | dirhtml:
60 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
61 | @echo
62 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
63 |
64 | singlehtml:
65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
66 | @echo
67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
68 |
69 | pickle:
70 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
71 | @echo
72 | @echo "Build finished; now you can process the pickle files."
73 |
74 | json:
75 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
76 | @echo
77 | @echo "Build finished; now you can process the JSON files."
78 |
79 | htmlhelp:
80 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
81 | @echo
82 | @echo "Build finished; now you can run HTML Help Workshop with the" \
83 | ".hhp project file in $(BUILDDIR)/htmlhelp."
84 |
85 | qthelp:
86 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
87 | @echo
88 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
89 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
90 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pluginmanager.qhcp"
91 | @echo "To view the help file:"
92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pluginmanager.qhc"
93 |
94 | applehelp:
95 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
96 | @echo
97 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
98 | @echo "N.B. You won't be able to view it unless you put it in" \
99 | "~/Library/Documentation/Help or install it in your application" \
100 | "bundle."
101 |
102 | devhelp:
103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
104 | @echo
105 | @echo "Build finished."
106 | @echo "To view the help file:"
107 | @echo "# mkdir -p $$HOME/.local/share/devhelp/pluginmanager"
108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pluginmanager"
109 | @echo "# devhelp"
110 |
111 | epub:
112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
113 | @echo
114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
115 |
116 | latex:
117 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
118 | @echo
119 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
120 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
121 | "(use \`make latexpdf' here to do that automatically)."
122 |
123 | latexpdf:
124 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
125 | @echo "Running LaTeX files through pdflatex..."
126 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
127 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
128 |
129 | latexpdfja:
130 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
131 | @echo "Running LaTeX files through platex and dvipdfmx..."
132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
134 |
135 | text:
136 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
137 | @echo
138 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
139 |
140 | man:
141 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
142 | @echo
143 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
144 |
145 | texinfo:
146 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
147 | @echo
148 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
149 | @echo "Run \`make' in that directory to run these through makeinfo" \
150 | "(use \`make info' here to do that automatically)."
151 |
152 | info:
153 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
154 | @echo "Running Texinfo files through makeinfo..."
155 | make -C $(BUILDDIR)/texinfo info
156 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
157 |
158 | gettext:
159 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
160 | @echo
161 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
162 |
163 | changes:
164 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
165 | @echo
166 | @echo "The overview file is in $(BUILDDIR)/changes."
167 |
168 | linkcheck:
169 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
170 | @echo
171 | @echo "Link check complete; look for any errors in the above output " \
172 | "or in $(BUILDDIR)/linkcheck/output.txt."
173 |
174 | doctest:
175 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
176 | @echo "Testing of doctests in the sources finished, look at the " \
177 | "results in $(BUILDDIR)/doctest/output.txt."
178 |
179 | coverage:
180 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
181 | @echo "Testing of coverage in the sources finished, look at the " \
182 | "results in $(BUILDDIR)/coverage/python.txt."
183 |
184 | xml:
185 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
186 | @echo
187 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
188 |
189 | pseudoxml:
190 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
191 | @echo
192 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
193 |
--------------------------------------------------------------------------------
/docs/source/conf.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | #
4 | # pluginmanager documentation build configuration file, created by
5 | # sphinx-quickstart on Wed Dec 9 22:32:56 2015.
6 | #
7 | # This file is execfile()d with the current directory set to its
8 | # containing dir.
9 | #
10 | # Note that not all possible configuration values are present in this
11 | # autogenerated file.
12 | #
13 | # All configuration values have a default; values that are commented out
14 | # serve to show the default.
15 |
16 | import sys
17 | import os
18 | import shlex
19 | from os import path
20 | root = path.realpath(path.join(path.dirname(__file__), '..', '..'))
21 | sys.path.insert(1, root)
22 | import pluginmanager
23 |
24 | doctest_path = [root]
25 | doctest_global_setup = "import pluginmanager"
26 | autodoc_default_flags = ['members']
27 | autosummary_generate = True
28 |
29 | # If extensions (or modules to document with autodoc) are in another directory,
30 | # add these directories to sys.path here. If the directory is relative to the
31 | # documentation root, use os.path.abspath to make it absolute, like shown here.
32 | #sys.path.insert(0, os.path.abspath('.'))
33 |
34 | # -- General configuration ------------------------------------------------
35 |
36 | # If your documentation needs a minimal Sphinx version, state it here.
37 | #needs_sphinx = '1.0'
38 |
39 | # Add any Sphinx extension module names here, as strings. They can be
40 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
41 | # ones.
42 | extensions = [
43 | 'sphinx.ext.doctest',
44 | 'sphinx.ext.viewcode',
45 | 'sphinx.ext.autodoc',
46 | 'sphinx.ext.autosummary',
47 | ]
48 |
49 | # Add any paths that contain templates here, relative to this directory.
50 | templates_path = ['_templates']
51 |
52 | # The suffix(es) of source filenames.
53 | # You can specify multiple suffix as a list of string:
54 | # source_suffix = ['.rst', '.md']
55 | source_suffix = '.rst'
56 |
57 | # The encoding of source files.
58 | #source_encoding = 'utf-8-sig'
59 |
60 | # The master toctree document.
61 | master_doc = 'index'
62 |
63 | # General information about the project.
64 | project = 'pluginmanager'
65 | copyright = '2015, Ben Hoff'
66 | author = 'Ben Hoff'
67 |
68 | # The version info for the project you're documenting, acts as replacement for
69 | # |version| and |release|, also used in various other places throughout the
70 | # built documents.
71 | #
72 | # The short X.Y version.
73 | version = '0.3.2'
74 | # The full version, including alpha/beta/rc tags.
75 | release = '0.3.1'
76 |
77 | # The language for content autogenerated by Sphinx. Refer to documentation
78 | # for a list of supported languages.
79 | #
80 | # This is also used if you do content translation via gettext catalogs.
81 | # Usually you set "language" from the command line for these cases.
82 | language = None
83 |
84 | # There are two options for replacing |today|: either, you set today to some
85 | # non-false value, then it is used:
86 | #today = ''
87 | # Else, today_fmt is used as the format for a strftime call.
88 | #today_fmt = '%B %d, %Y'
89 |
90 | # List of patterns, relative to source directory, that match files and
91 | # directories to ignore when looking for source files.
92 | exclude_patterns = []
93 |
94 | # The reST default role (used for this markup: `text`) to use for all
95 | # documents.
96 | #default_role = None
97 |
98 | # If true, '()' will be appended to :func: etc. cross-reference text.
99 | #add_function_parentheses = True
100 |
101 | # If true, the current module name will be prepended to all description
102 | # unit titles (such as .. function::).
103 | #add_module_names = True
104 |
105 | # If true, sectionauthor and moduleauthor directives will be shown in the
106 | # output. They are ignored by default.
107 | #show_authors = False
108 |
109 | # The name of the Pygments (syntax highlighting) style to use.
110 | pygments_style = 'sphinx'
111 |
112 | # A list of ignored prefixes for module index sorting.
113 | #modindex_common_prefix = []
114 |
115 | # If true, keep warnings as "system message" paragraphs in the built documents.
116 | #keep_warnings = False
117 |
118 | # If true, `todo` and `todoList` produce output, else they produce nothing.
119 | todo_include_todos = False
120 |
121 |
122 | # -- Options for HTML output ----------------------------------------------
123 |
124 | # The theme to use for HTML and HTML Help pages. See the documentation for
125 | # a list of builtin themes.
126 | html_theme = 'alabaster'
127 |
128 | # Theme options are theme-specific and customize the look and feel of a theme
129 | # further. For a list of options available for each theme, see the
130 | # documentation.
131 | #html_theme_options = {}
132 |
133 | # Add any paths that contain custom themes here, relative to this directory.
134 | #html_theme_path = []
135 |
136 | # The name for this set of Sphinx documents. If None, it defaults to
137 | # " v documentation".
138 | #html_title = None
139 |
140 | # A shorter title for the navigation bar. Default is the same as html_title.
141 | #html_short_title = None
142 |
143 | # The name of an image file (relative to this directory) to place at the top
144 | # of the sidebar.
145 | #html_logo = None
146 |
147 | # The name of an image file (within the static path) to use as favicon of the
148 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
149 | # pixels large.
150 | #html_favicon = None
151 |
152 | # Add any paths that contain custom static files (such as style sheets) here,
153 | # relative to this directory. They are copied after the builtin static files,
154 | # so a file named "default.css" will overwrite the builtin "default.css".
155 | html_static_path = ['_static']
156 |
157 | # Add any extra paths that contain custom files (such as robots.txt or
158 | # .htaccess) here, relative to this directory. These files are copied
159 | # directly to the root of the documentation.
160 | #html_extra_path = []
161 |
162 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
163 | # using the given strftime format.
164 | #html_last_updated_fmt = '%b %d, %Y'
165 |
166 | # If true, SmartyPants will be used to convert quotes and dashes to
167 | # typographically correct entities.
168 | #html_use_smartypants = True
169 |
170 | # Custom sidebar templates, maps document names to template names.
171 | #html_sidebars = {}
172 |
173 | # Additional templates that should be rendered to pages, maps page names to
174 | # template names.
175 | #html_additional_pages = {}
176 |
177 | # If false, no module index is generated.
178 | #html_domain_indices = True
179 |
180 | # If false, no index is generated.
181 | #html_use_index = True
182 |
183 | # If true, the index is split into individual pages for each letter.
184 | #html_split_index = False
185 |
186 | # If true, links to the reST sources are added to the pages.
187 | #html_show_sourcelink = True
188 |
189 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
190 | #html_show_sphinx = True
191 |
192 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
193 | #html_show_copyright = True
194 |
195 | # If true, an OpenSearch description file will be output, and all pages will
196 | # contain a tag referring to it. The value of this option must be the
197 | # base URL from which the finished HTML is served.
198 | #html_use_opensearch = ''
199 |
200 | # This is the file name suffix for HTML files (e.g. ".xhtml").
201 | #html_file_suffix = None
202 |
203 | # Language to be used for generating the HTML full-text search index.
204 | # Sphinx supports the following languages:
205 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
206 | # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
207 | #html_search_language = 'en'
208 |
209 | # A dictionary with options for the search language support, empty by default.
210 | # Now only 'ja' uses this config value
211 | #html_search_options = {'type': 'default'}
212 |
213 | # The name of a javascript file (relative to the configuration directory) that
214 | # implements a search results scorer. If empty, the default will be used.
215 | #html_search_scorer = 'scorer.js'
216 |
217 | # Output file base name for HTML help builder.
218 | htmlhelp_basename = 'pluginmanagerdoc'
219 |
220 | # -- Options for LaTeX output ---------------------------------------------
221 |
222 | latex_elements = {
223 | # The paper size ('letterpaper' or 'a4paper').
224 | #'papersize': 'letterpaper',
225 |
226 | # The font size ('10pt', '11pt' or '12pt').
227 | #'pointsize': '10pt',
228 |
229 | # Additional stuff for the LaTeX preamble.
230 | #'preamble': '',
231 |
232 | # Latex figure (float) alignment
233 | #'figure_align': 'htbp',
234 | }
235 |
236 | # Grouping the document tree into LaTeX files. List of tuples
237 | # (source start file, target name, title,
238 | # author, documentclass [howto, manual, or own class]).
239 | latex_documents = [
240 | (master_doc, 'pluginmanager.tex', 'pluginmanager Documentation',
241 | 'Ben Hoff', 'manual'),
242 | ]
243 |
244 | # The name of an image file (relative to this directory) to place at the top of
245 | # the title page.
246 | #latex_logo = None
247 |
248 | # For "manual" documents, if this is true, then toplevel headings are parts,
249 | # not chapters.
250 | #latex_use_parts = False
251 |
252 | # If true, show page references after internal links.
253 | #latex_show_pagerefs = False
254 |
255 | # If true, show URL addresses after external links.
256 | #latex_show_urls = False
257 |
258 | # Documents to append as an appendix to all manuals.
259 | #latex_appendices = []
260 |
261 | # If false, no module index is generated.
262 | #latex_domain_indices = True
263 |
264 |
265 | # -- Options for manual page output ---------------------------------------
266 |
267 | # One entry per manual page. List of tuples
268 | # (source start file, name, description, authors, manual section).
269 | man_pages = [
270 | (master_doc, 'pluginmanager', 'pluginmanager Documentation',
271 | [author], 1)
272 | ]
273 |
274 | # If true, show URL addresses after external links.
275 | #man_show_urls = False
276 |
277 |
278 | # -- Options for Texinfo output -------------------------------------------
279 |
280 | # Grouping the document tree into Texinfo files. List of tuples
281 | # (source start file, target name, title, author,
282 | # dir menu entry, description, category)
283 | texinfo_documents = [
284 | (master_doc, 'pluginmanager', 'pluginmanager Documentation',
285 | author, 'pluginmanager', 'One line description of project.',
286 | 'Miscellaneous'),
287 | ]
288 |
289 | # Documents to append as an appendix to all manuals.
290 | #texinfo_appendices = []
291 |
292 | # If false, no module index is generated.
293 | #texinfo_domain_indices = True
294 |
295 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
296 | #texinfo_show_urls = 'footnote'
297 |
298 | # If true, do not generate a @detailmenu in the "Top" node's menu.
299 | #texinfo_no_detailmenu = False
300 |
--------------------------------------------------------------------------------
/docs/source/index.rst:
--------------------------------------------------------------------------------
1 | .. pluginmanager documentation master file, created by
2 | sphinx-quickstart on Wed Dec 9 22:32:56 2015.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | .. testsetup:: quickstart
7 |
8 | import os
9 | from pluginmanager.tests.compat import tempfile
10 | tempdirectory = tempfile.TemporaryDirectory()
11 | plugin_directory_path = tempdirectory.name
12 | path = os.path.join(tempdirectory.name, 'test.py')
13 | with open(path, 'w+') as f:
14 | f.write('from pluginmanager import IPlugin\nclass Test(IPlugin):\n pass')
15 |
16 | pluginmanager
17 | =============
18 | |Build Status| |Coverage Status| |Code Climate|
19 |
20 | python plugin management, simplified.
21 |
22 | `Source Code `_
23 |
24 | Library under development. Contains rough edges/unfinished functionality. API subject to changes.
25 |
26 | Installation
27 | ------------
28 |
29 | ::
30 |
31 | pip install pluginmanager
32 |
33 | -or- ::
34 |
35 | pip install git+https://github.com/benhoff/pluginmanager.git
36 |
37 | Quickstart
38 | ----------
39 |
40 | .. testcode:: quickstart
41 |
42 | from pluginmanager import PluginInterface
43 |
44 | plugin_interface = PluginInterface()
45 | plugin_interface.set_plugin_directories(plugin_directory_path)
46 | plugin_interface.collect_plugins() # doctest: +SKIP
47 |
48 | plugins = plugin_interface.get_instances()
49 | print(plugins)
50 |
51 | .. testoutput:: quickstart
52 | :hide:
53 | :options: +ELLIPSIS
54 |
55 | [= 4:
58 | # flake8: noqa
59 | import importlib
60 |
61 | def load_source(name, file_path):
62 | loader = importlib.machinery.SourceFileLoader(name, file_path)
63 | return loader.load_module()
64 | else:
65 | # flake8: noqa
66 | import imp
67 | load_source = imp.load_source
68 |
--------------------------------------------------------------------------------
/pluginmanager/directory_manager.py:
--------------------------------------------------------------------------------
1 | import os
2 | from .compat import getsitepackages
3 |
4 | from pluginmanager import util
5 |
6 |
7 | class DirectoryManager(object):
8 | """
9 | `DirectoryManager` manages the recursive search state and can
10 | optionally manage directory state. The default implementation of
11 | pluginmanager uses `DirectoryManager` to manage the directory state.
12 |
13 | `DirectoryManager` contains a directory blacklist, which can be used to
14 | stop from collecting from uninteresting directories.
15 |
16 | `DirectoryManager` manages directory state through the add/get/set
17 | directories methods.
18 |
19 | NOTE: When calling `collect_directories` the directories must be
20 | explicitly passed into the method call. This is to avoid tight coupling
21 | from the internal state and promote reuse at the Interface level.
22 | """
23 | def __init__(self,
24 | plugin_directories=None,
25 | recursive=True,
26 | blacklisted_directories=None):
27 | """
28 | `recursive` is used to control whether directories are searched
29 | recursviely or not
30 |
31 | `plugin_directories` may be a single directories or an iterable.
32 |
33 | `blacklisted_directories` may be a single directory or an iterable
34 | """
35 |
36 | self.recursive = recursive
37 | self.plugin_directories = None
38 | self.blacklisted_directories = None
39 | if plugin_directories is None:
40 | plugin_directories = set()
41 | if blacklisted_directories is None:
42 | blacklisted_directories = set()
43 |
44 | self.set_directories(plugin_directories)
45 | self.set_blacklisted_directories(blacklisted_directories)
46 |
47 | def collect_directories(self, directories):
48 | """
49 | Collects all the directories into a `set` object.
50 |
51 | If `self.recursive` is set to `True` this method will iterate through
52 | and return all of the directories and the subdirectories found from
53 | `directories` that are not blacklisted.
54 |
55 | if `self.recursive` is set to `False` this will return all the
56 | directories that are not balcklisted.
57 |
58 | `directories` may be either a single object or an iterable. Recommend
59 | passing in absolute paths instead of relative. `collect_directories`
60 | will attempt to convert `directories` to absolute paths if they are not
61 | already.
62 | """
63 | directories = util.to_absolute_paths(directories)
64 |
65 | if not self.recursive:
66 | return self._remove_blacklisted(directories)
67 |
68 | recursive_dirs = set()
69 | for dir_ in directories:
70 | walk_iter = os.walk(dir_, followlinks=True)
71 | walk_iter = [w[0] for w in walk_iter]
72 | walk_iter = util.to_absolute_paths(walk_iter)
73 | walk_iter = self._remove_blacklisted(walk_iter)
74 | recursive_dirs.update(walk_iter)
75 | return recursive_dirs
76 |
77 | def add_directories(self, directories, except_blacklisted=True):
78 | """
79 | Adds `directories` to the set of plugin directories.
80 |
81 | `directories` may be either a single object or a iterable.
82 |
83 | `directories` can be relative paths, but will be converted into
84 | absolute paths based on the current working directory.
85 |
86 | if `except_blacklisted` is `True` all `directories` in
87 | `self.blacklisted_directories` will be removed
88 | """
89 | directories = util.to_absolute_paths(directories)
90 | if except_blacklisted:
91 | directories = self._remove_blacklisted(directories)
92 |
93 | self.plugin_directories.update(directories)
94 |
95 | def set_directories(self, directories, except_blacklisted=True):
96 | """
97 | Sets the plugin directories to `directories`. This will delete
98 | the previous state stored in `self.plugin_directories` in favor
99 | of the `directories` passed in.
100 |
101 | `directories` may be either a single object or an iterable.
102 |
103 | `directories` can contain relative paths but will be
104 | converted into absolute paths based on the current working
105 | directory.
106 |
107 | if `except_blacklisted` is `True` all `directories` in
108 | `self.blacklisted_directories` will be removed
109 | """
110 | directories = util.to_absolute_paths(directories)
111 | if except_blacklisted:
112 | directories = self._remove_blacklisted(directories)
113 |
114 | self.plugin_directories = directories
115 |
116 | def remove_directories(self, directories):
117 | """
118 | Removes any `directories` from the set of plugin directories.
119 |
120 | `directories` may be a single object or an iterable.
121 |
122 | Recommend passing in all paths as absolute, but the method will
123 | attemmpt to convert all paths to absolute if they are not already
124 | based on the current working directory.
125 | """
126 | directories = util.to_absolute_paths(directories)
127 | self.plugin_directories = util.remove_from_set(self.plugin_directories,
128 | directories)
129 |
130 | def add_site_packages_paths(self):
131 | """
132 | A helper method to add all of the site packages tracked by python
133 | to the set of plugin directories.
134 |
135 | NOTE that if using a virtualenv, there is an outstanding bug with the
136 | method used here. While there is a workaround implemented, when using a
137 | virutalenv this method WILL NOT track every single path tracked by
138 | python. See: https://github.com/pypa/virtualenv/issues/355
139 | """
140 | site_packages = getsitepackages()
141 | self.add_directories(site_packages)
142 |
143 | def add_blacklisted_directories(self,
144 | directories,
145 | remove_from_stored_directories=True):
146 |
147 | """
148 | Adds `directories` to be blacklisted. Blacklisted directories will not
149 | be returned or searched recursively when calling the
150 | `collect_directories` method.
151 |
152 | `directories` may be a single instance or an iterable. Recommend
153 | passing in absolute paths, but method will try to convert to absolute
154 | paths based on the current working directory.
155 |
156 | If `remove_from_stored_directories` is true, all `directories`
157 | will be removed from `self.plugin_directories`
158 | """
159 | absolute_paths = util.to_absolute_paths(directories)
160 | self.blacklisted_directories.update(absolute_paths)
161 | if remove_from_stored_directories:
162 | plug_dirs = self.plugin_directories
163 | plug_dirs = util.remove_from_set(plug_dirs,
164 | directories)
165 |
166 | def set_blacklisted_directories(self,
167 | directories,
168 | remove_from_stored_directories=True):
169 | """
170 | Sets the `directories` to be blacklisted. Blacklisted directories will
171 | not be returned or searched recursively when calling
172 | `collect_directories`.
173 |
174 | This will replace the previously stored set of blacklisted
175 | paths.
176 |
177 | `directories` may be a single instance or an iterable. Recommend
178 | passing in absolute paths. Method will try to convert to absolute path
179 | based on current working directory.
180 | """
181 | absolute_paths = util.to_absolute_paths(directories)
182 | self.blacklisted_directories = absolute_paths
183 | if remove_from_stored_directories:
184 | plug_dirs = self.plugin_directories
185 | plug_dirs = util.remove_from_set(plug_dirs,
186 | directories)
187 |
188 | def get_blacklisted_directories(self):
189 | """
190 | Returns the set of the blacklisted directories.
191 | """
192 | return self.blacklisted_directories
193 |
194 | def remove_blacklisted_directories(self, directories):
195 | """
196 | Attempts to remove the `directories` from the set of blacklisted
197 | directories. If a particular directory is not found in the set of
198 | blacklisted, method will continue on silently.
199 |
200 | `directories` may be a single instance or an iterable. Recommend
201 | passing in absolute paths. Method will try to convert to an absolute
202 | path if it is not already using the current working directory.
203 | """
204 | directories = util.to_absolute_paths(directories)
205 | black_dirs = self.blacklisted_directories
206 | black_dirs = util.remove_from_set(black_dirs, directories)
207 |
208 | def _remove_blacklisted(self, directories):
209 | """
210 | Attempts to remove the blacklisted directories from `directories`
211 | and then returns whatever is left in the set.
212 |
213 | Called from the `collect_directories` method.
214 | """
215 | directories = util.to_absolute_paths(directories)
216 | directories = util.remove_from_set(directories,
217 | self.blacklisted_directories)
218 |
219 | return directories
220 |
221 | def get_directories(self):
222 | """
223 | Returns the plugin directories in a `set` object
224 | """
225 | return self.plugin_directories
226 |
--------------------------------------------------------------------------------
/pluginmanager/entry_point_manager.py:
--------------------------------------------------------------------------------
1 | import pkg_resources
2 | from pluginmanager import util
3 |
4 |
5 | class EntryPointManager(object):
6 | """
7 | Entry points are an advanced python packaging systems whereby installing
8 | using pip automagically makes the package available to the program.
9 | This class manages the state associated with the entry points and is
10 | responsible for collecting plugins using entry points.
11 | """
12 | def __init__(self, entry_point_names=None):
13 | if entry_point_names is None:
14 | entry_point_names = set()
15 |
16 | self.entry_point_names = util.return_set(entry_point_names)
17 |
18 | def add_entry_points(self, names):
19 | """
20 | adds `names` to the internal collection of entry points to track
21 |
22 | `names` can be a single object or an iterable but
23 | must be a string or iterable of strings.
24 | """
25 | names = util.return_set(names)
26 | self.entry_point_names.update(names)
27 |
28 | def set_entry_points(self, names):
29 | """
30 | sets the internal collection of entry points to be
31 | equal to `names`
32 |
33 | `names` can be a single object or an iterable but
34 | must be a string or iterable of strings.
35 | """
36 | names = util.return_set(names)
37 | self.entry_point_names = names
38 |
39 | def remove_entry_points(self, names):
40 | """
41 | removes `names` from the set of entry points to track.
42 |
43 | `names` can be a single object or an iterable.
44 | """
45 | names = util.return_set(names)
46 | util.remove_from_set(self.entry_point_names,
47 | names)
48 |
49 | def get_entry_points(self):
50 | """
51 | returns a set of all the entry points tracked internally
52 | """
53 | return self.entry_point_names
54 |
55 | def collect_plugins(self,
56 | entry_points=None,
57 | verify_requirements=False,
58 | return_dict=False):
59 |
60 | """
61 | collects the plugins from the `entry_points`. If `entry_points` is not
62 | explicitly defined, this method will pull from the internal state
63 | defined using the add/set entry points methods.
64 |
65 | `entry_points` can be a single object or an iterable, but must be
66 | either a string or an iterable of strings.
67 |
68 | returns a list of plugins or an empty list.
69 | """
70 |
71 | if entry_points is None:
72 | entry_points = self.entry_point_names
73 | else:
74 | entry_points = util.return_set(entry_points)
75 |
76 | plugins = []
77 | plugin_names = []
78 | for name in entry_points:
79 | for entry_point in pkg_resources.iter_entry_points(name):
80 | if (hasattr(entry_point, 'resolve') and
81 | hasattr(entry_point, 'require')):
82 |
83 | if verify_requirements:
84 | entry_point.require()
85 |
86 | plugin = entry_point.resolve()
87 | else:
88 | plugin = entry_point.load()
89 |
90 | plugins.append(plugin)
91 | plugin_names.append(entry_point.name)
92 |
93 | if return_dict:
94 | return {n: v for n, v in zip(plugin_names, plugins)}
95 |
96 | return plugins, plugin_names
97 |
--------------------------------------------------------------------------------
/pluginmanager/file_filters/__init__.py:
--------------------------------------------------------------------------------
1 | from ._forbidden_name import PLUGIN_FORBIDDEN_NAME # flake8: noqa
2 | from .with_info_file import WithInfoFileFilter
3 | from .matching_regex import MatchingRegexFileFilter
4 | from .filenames import FilenameFileFilter
5 |
6 |
7 | __all__ = ["WithInfoFileFilter",
8 | "MatchingRegexFileFilter",
9 | "FilenameFileFilter"]
10 |
--------------------------------------------------------------------------------
/pluginmanager/file_filters/_forbidden_name.py:
--------------------------------------------------------------------------------
1 | PLUGIN_FORBIDDEN_NAME = ';;'
2 |
--------------------------------------------------------------------------------
/pluginmanager/file_filters/filenames.py:
--------------------------------------------------------------------------------
1 | import os
2 | from pluginmanager import util
3 |
4 |
5 | class FilenameFileFilter(object):
6 | def __init__(self, filenames='__init__.py'):
7 | filenames = util.return_list(filenames)
8 | self.filenames = filenames
9 |
10 | def __call__(self, filepaths):
11 | plugin_filepaths = []
12 | for filepath in filepaths:
13 | if self.plugin_valid(filepath):
14 | plugin_filepaths.append(filepath)
15 | return plugin_filepaths
16 |
17 | def plugin_valid(self, filename):
18 | filename = os.path.basename(filename)
19 | if filename in self.filenames:
20 | return True
21 | return False
22 |
--------------------------------------------------------------------------------
/pluginmanager/file_filters/matching_regex.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 |
4 |
5 | class MatchingRegexFileFilter(object):
6 | """
7 | An analyzer that targets plugins decribed by files whose
8 | name match a given regex.
9 | """
10 | def __init__(self, regexp):
11 | if not isinstance(regexp, list):
12 | regexp = [regexp]
13 | regex_expressions = []
14 | for regex in regexp:
15 | regex_expressions.append(re.compile(regex))
16 | self.regex_expressions = regex_expressions
17 |
18 | def __call__(self, filepaths):
19 | plugin_filepaths = []
20 | for filepath in filepaths:
21 | if self.plugin_valid(filepath):
22 | plugin_filepaths.append(filepath)
23 | return plugin_filepaths
24 |
25 | def set_regex_expressions(self, regex_expressions):
26 | if not isinstance(regex_expressions, list):
27 | regex_expressions = [regex_expressions]
28 | self.regex_expressions = regex_expressions
29 |
30 | def add_regex_expressions(self, regex_expressions):
31 | if not isinstance(regex_expressions, list):
32 | regex_expressions = [regex_expressions]
33 | self.regex_expressions.extend(regex_expressions)
34 |
35 | def plugin_valid(self, filename):
36 | """
37 | Checks if the given filename is a valid plugin for this Strategy
38 | """
39 | filename = os.path.basename(filename)
40 | for regex in self.regex_expressions:
41 | if regex.match(filename):
42 | return True
43 | return False
44 |
--------------------------------------------------------------------------------
/pluginmanager/file_filters/with_info_file.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 | from pluginmanager import util
4 | from pluginmanager.compat import ConfigParser, FILE_ERROR
5 | from . import PLUGIN_FORBIDDEN_NAME
6 |
7 |
8 | class WithInfoFileFilter(object):
9 | """
10 | Only gets files that have configuration files ending with specific
11 | extensions, nominally 'yapsy-plugin'
12 | """
13 | def __init__(self, extensions='yapsy-plugin'):
14 | self.extensions = util.return_list(extensions)
15 |
16 | def set_file_extensions(self, extensions):
17 | extensions = util.return_list(extensions)
18 | self.extensions = extensions
19 |
20 | def add_file_extensions(self, extensions):
21 | extensions = util.return_list(extensions)
22 | self.extensions.extend(extensions)
23 |
24 | def __call__(self, filepaths):
25 | return self.get_plugin_filepaths(filepaths)
26 |
27 | def get_info_and_filepaths(self, filepaths):
28 | plugin_information = self.get_plugin_infos(filepaths)
29 | plugin_filepaths = self.get_plugin_filepaths(filepaths,
30 | plugin_information)
31 |
32 | return plugin_information, plugin_filepaths
33 |
34 | def get_plugin_filepaths(self, filepaths, plugin_infos=None):
35 | # Enforce uniqueness of filepaths in `PluginLocator`
36 | plugin_filepaths = set()
37 | # if we've already got the infos list, get plugin filepath from those
38 | if plugin_infos is None:
39 | plugin_infos = self.get_plugin_infos(filepaths)
40 |
41 | for plugin_info in plugin_infos:
42 | path = plugin_info['path']
43 | plugin_filepaths.add(path)
44 |
45 | return plugin_filepaths
46 |
47 | def plugin_valid(self, filepath):
48 | """
49 | checks to see if plugin ends with one of the
50 | approved extensions
51 | """
52 | plugin_valid = False
53 | for extension in self.extensions:
54 | if filepath.endswith(".{}".format(extension)):
55 | plugin_valid = True
56 | break
57 | return plugin_valid
58 |
59 | def get_plugin_infos(self, filepaths):
60 | plugin_infos = []
61 |
62 | config_parser = ConfigParser()
63 | config_filepaths = config_parser.read(filepaths)
64 |
65 | for config_filepath in config_filepaths:
66 | if self.plugin_valid(config_filepath):
67 | dir_path, _ = os.path.split(config_filepath)
68 | config_dict = {}
69 |
70 | with open(config_filepath) as f:
71 | config_parser.read_file(f)
72 | config_dict = self._parse_config_details(config_parser,
73 | dir_path)
74 |
75 | if self._valid_config(config_dict):
76 | plugin_infos.append(config_dict)
77 |
78 | return plugin_infos
79 |
80 | def _parse_config_details(self, config_parser, dir_path):
81 | # get all data out of config_parser
82 | config_dict = {s: {k: v for k, v in config_parser.items(s)} for s in config_parser.sections()} # noqa
83 |
84 | # now remove and parse data stored in "Core" key
85 | core_config = config_dict.pop("Core")
86 |
87 | # change and store the relative path in Module to absolute
88 | relative_path = core_config.pop('module')
89 | path = os.path.join(dir_path, relative_path)
90 |
91 | if os.path.isfile(path + '.py'):
92 | path += '.py'
93 | elif (os.path.isdir(path) and
94 | os.path.isfile(os.path.join(path, '__init__.py'))):
95 | path = os.path.join(path, '__init__.py')
96 | else:
97 | raise FILE_ERROR('{} not a `.py` file or a dir'.format(path))
98 |
99 | config_dict['path'] = path
100 |
101 | # grab and store the name, strip whitespace
102 | config_dict['name'] = core_config["name"].strip()
103 | return config_dict
104 |
105 | def _valid_config(self, config):
106 | valid_config = False
107 | if "name" in config and "path" in config:
108 | valid_config = True
109 |
110 | name = config['name']
111 | name = name.strip()
112 | if PLUGIN_FORBIDDEN_NAME in name:
113 | valid_config = False
114 |
115 | return valid_config
116 |
--------------------------------------------------------------------------------
/pluginmanager/file_manager.py:
--------------------------------------------------------------------------------
1 | from pluginmanager import util
2 |
3 |
4 | class FileManager(object):
5 | """
6 | `FileManager` manages the file filter state and is responible for
7 | collecting filepaths from a set of directories and filtering the files
8 | through the filters. Without file filters, this class acts as a
9 | passthrough, collecting and returning every file in a given directory.
10 |
11 | `FileManager` can also optionally manage the plugin filepath state through
12 | the use of the add/get/set plugin filepaths methods. Note that plugin
13 | interface is not automatically set up this way, although it is
14 | relatively trivial to do.
15 | """
16 | def __init__(self,
17 | file_filters=None,
18 | plugin_filepaths=None,
19 | blacklisted_filepaths=None):
20 |
21 | """
22 | `FileFilters` are callable filters. Each filter must take in a
23 | set of filepaths and return back a set of filepaths. Each filter
24 | is applied independently to the set of filepaths and added to the
25 | return set.
26 | `FileFilters` can be a single object or an iterable
27 |
28 | `plugin_filepaths` are known plugin filepaths that can be stored
29 | in `FileManager`. Note that filepaths stored in the plugin filepaths
30 | are NOT automatically added when calling the `collect_filepaths`
31 | method. Recommend using absolute paths. `plugin_filepaths` can be a
32 | single object or an interable.
33 |
34 | `blacklisted_filepaths` are plugin filepaths that are not to be
35 | included in the collected filepaths. Recommend using absolute paths.
36 | `blacklisted_filepaths` can be a single object or an iterable.
37 | """
38 |
39 | if file_filters is None:
40 | file_filters = []
41 | if plugin_filepaths is None:
42 | plugin_filepaths = set()
43 | if blacklisted_filepaths is None:
44 | blacklisted_filepaths = set()
45 |
46 | self.file_filters = util.return_list(file_filters)
47 | # pep8
48 | to_abs_paths = util.to_absolute_paths
49 |
50 | self.plugin_filepaths = to_abs_paths(plugin_filepaths)
51 | self.blacklisted_filepaths = to_abs_paths(blacklisted_filepaths)
52 |
53 | def collect_filepaths(self, directories):
54 | """
55 | Collects and returns every filepath from each directory in
56 | `directories` that is filtered through the `file_filters`.
57 | If no `file_filters` are present, passes every file in directory
58 | as a result.
59 | Always returns a `set` object
60 |
61 | `directories` can be a object or an iterable. Recommend using
62 | absolute paths.
63 | """
64 | plugin_filepaths = set()
65 | directories = util.to_absolute_paths(directories)
66 | for directory in directories:
67 | filepaths = util.get_filepaths_from_dir(directory)
68 | filepaths = self._filter_filepaths(filepaths)
69 | plugin_filepaths.update(set(filepaths))
70 |
71 | plugin_filepaths = self._remove_blacklisted(plugin_filepaths)
72 |
73 | return plugin_filepaths
74 |
75 | def add_plugin_filepaths(self, filepaths, except_blacklisted=True):
76 | """
77 | Adds `filepaths` to the `self.plugin_filepaths`. Recommend passing
78 | in absolute filepaths. Method will attempt to convert to
79 | absolute paths if they are not already.
80 |
81 | `filepaths` can be a single object or an iterable
82 |
83 | If `except_blacklisted` is `True`, all `filepaths` that
84 | have been blacklisted will not be added.
85 | """
86 | filepaths = util.to_absolute_paths(filepaths)
87 | if except_blacklisted:
88 | filepaths = util.remove_from_set(filepaths,
89 | self.blacklisted_filepaths)
90 |
91 | self.plugin_filepaths.update(filepaths)
92 |
93 | def set_plugin_filepaths(self, filepaths, except_blacklisted=True):
94 | """
95 | Sets `filepaths` to the `self.plugin_filepaths`. Recommend passing
96 | in absolute filepaths. Method will attempt to convert to
97 | absolute paths if they are not already.
98 |
99 | `filepaths` can be a single object or an iterable.
100 |
101 | If `except_blacklisted` is `True`, all `filepaths` that
102 | have been blacklisted will not be set.
103 | """
104 | filepaths = util.to_absolute_paths(filepaths)
105 | if except_blacklisted:
106 | filepaths = util.remove_from_set(filepaths,
107 | self.blacklisted_filepaths)
108 |
109 | self.plugin_filepaths = filepaths
110 |
111 | def remove_plugin_filepaths(self, filepaths):
112 | """
113 | Removes `filepaths` from `self.plugin_filepaths`.
114 | Recommend passing in absolute filepaths. Method will
115 | attempt to convert to absolute paths if not passed in.
116 |
117 | `filepaths` can be a single object or an iterable.
118 | """
119 | filepaths = util.to_absolute_paths(filepaths)
120 | self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths,
121 | filepaths)
122 |
123 | def get_plugin_filepaths(self):
124 | """
125 | returns the plugin filepaths tracked internally as a `set` object.
126 | """
127 | return self.plugin_filepaths
128 |
129 | def set_file_filters(self, file_filters):
130 | """
131 | Sets internal file filters to `file_filters` by tossing old state.
132 | `file_filters` can be single object or iterable.
133 | """
134 | file_filters = util.return_list(file_filters)
135 | self.file_filters = file_filters
136 |
137 | def add_file_filters(self, file_filters):
138 | """
139 | Adds `file_filters` to the internal file filters.
140 | `file_filters` can be single object or iterable.
141 | """
142 | file_filters = util.return_list(file_filters)
143 | self.file_filters.extend(file_filters)
144 |
145 | def remove_file_filters(self, file_filters):
146 | """
147 | Removes the `file_filters` from the internal state.
148 | `file_filters` can be a single object or an iterable.
149 | """
150 | self.file_filters = util.remove_from_list(self.file_filters,
151 | file_filters)
152 |
153 | def get_file_filters(self, filter_function=None):
154 | """
155 | Gets the file filters.
156 | `filter_function`, can be a user defined filter. Should be callable
157 | and return a list.
158 | """
159 | if filter_function is None:
160 | return self.file_filters
161 | else:
162 | return filter_function(self.file_filters)
163 |
164 | def add_blacklisted_filepaths(self, filepaths, remove_from_stored=True):
165 | """
166 | Add `filepaths` to blacklisted filepaths.
167 | If `remove_from_stored` is `True`, any `filepaths` in
168 | `plugin_filepaths` will be automatically removed.
169 |
170 | Recommend passing in absolute filepaths but method will attempt
171 | to convert to absolute filepaths based on current working directory.
172 | """
173 | filepaths = util.to_absolute_paths(filepaths)
174 | self.blacklisted_filepaths.update(filepaths)
175 | if remove_from_stored:
176 | self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths,
177 | filepaths)
178 |
179 | def set_blacklisted_filepaths(self, filepaths, remove_from_stored=True):
180 | """
181 | Sets internal blacklisted filepaths to filepaths.
182 | If `remove_from_stored` is `True`, any `filepaths` in
183 | `self.plugin_filepaths` will be automatically removed.
184 |
185 | Recommend passing in absolute filepaths but method will attempt
186 | to convert to absolute filepaths based on current working directory.
187 | """
188 | filepaths = util.to_absolute_paths(filepaths)
189 | self.blacklisted_filepaths = filepaths
190 | if remove_from_stored:
191 | self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths,
192 | filepaths)
193 |
194 | def remove_blacklisted_filepaths(self, filepaths):
195 | """
196 | Removes `filepaths` from blacklisted filepaths
197 |
198 | Recommend passing in absolute filepaths but method will attempt
199 | to convert to absolute filepaths based on current working directory.
200 | """
201 | filepaths = util.to_absolute_paths(filepaths)
202 | black_paths = self.blacklisted_filepaths
203 | black_paths = util.remove_from_set(black_paths, filepaths)
204 |
205 | def get_blacklisted_filepaths(self):
206 | """
207 | Returns the blacklisted filepaths as a set object.
208 | """
209 | return self.blacklisted_filepaths
210 |
211 | def _remove_blacklisted(self, filepaths):
212 | """
213 | internal helper method to remove the blacklisted filepaths
214 | from `filepaths`.
215 | """
216 | filepaths = util.remove_from_set(filepaths, self.blacklisted_filepaths)
217 | return filepaths
218 |
219 | def _filter_filepaths(self, filepaths):
220 | """
221 | helps iterate through all the file parsers
222 | each filter is applied individually to the
223 | same set of `filepaths`
224 | """
225 | if self.file_filters:
226 | plugin_filepaths = set()
227 | for file_filter in self.file_filters:
228 | plugin_paths = file_filter(filepaths)
229 | plugin_filepaths.update(plugin_paths)
230 | else:
231 | plugin_filepaths = filepaths
232 |
233 | return plugin_filepaths
234 |
--------------------------------------------------------------------------------
/pluginmanager/iplugin.py:
--------------------------------------------------------------------------------
1 | import abc
2 | from .compat import with_metaclass
3 |
4 |
5 | class IPlugin(with_metaclass(abc.ABCMeta)):
6 | """
7 | Simple interface to be inherited when creating a plugin.
8 | """
9 | CONFIGURATION_TEMPLATE = {'shared': {}}
10 |
11 | def __init__(self):
12 | self.active = False
13 | self.configuration = None
14 | try:
15 | getattr(self, 'name')
16 | except AttributeError:
17 | self.name = self.__class__.__name__
18 |
19 | def activate(self):
20 | """
21 | Called at plugin activation.
22 | """
23 | self.active = True
24 |
25 | def deactivate(self):
26 | """
27 | Called when the plugin is disabled.
28 | """
29 | self.active = False
30 |
31 | def get_configuration_template(self):
32 | """
33 | If your plugin needs a configuration, override this method and return
34 | a configuration template.
35 | For example a dictionary like:
36 | return {'LOGIN' : 'example@example.com', 'PASSWORD' : 'password'}
37 | Note: if this method returns None, the plugin won't be configured
38 | """
39 | return self.CONFIGURATION_TEMPLATE
40 |
41 | def check_configuration(self, configuration):
42 | config_template = self.get_configuration_template()
43 | for key in config_template.keys():
44 | if key not in configuration:
45 | error = '{} doesn\'t contain the key {}'.format(configuration,
46 | key)
47 |
48 | raise Exception(error)
49 | return True
50 |
51 | def configure(self, configuration):
52 | self.configuration = configuration
53 |
--------------------------------------------------------------------------------
/pluginmanager/module_filters/__init__.py:
--------------------------------------------------------------------------------
1 | from .subclass_parser import SubclassParser
2 | from .keyword_parser import KeywordParser
3 |
4 | __all__ = ["SubclassParser", "KeywordParser"]
5 |
--------------------------------------------------------------------------------
/pluginmanager/module_filters/keyword_parser.py:
--------------------------------------------------------------------------------
1 | from pluginmanager import util
2 |
3 |
4 | class KeywordParser(object):
5 | def __init__(self, keywords='PLUGINS'):
6 | keywords = util.return_list(keywords)
7 | self.keywords = keywords
8 |
9 | def __call__(self, plugins, names):
10 | result = []
11 | for plugin, name in zip(plugins, names):
12 | if name in self.keywords:
13 | result.append(plugin)
14 | return result
15 |
--------------------------------------------------------------------------------
/pluginmanager/module_filters/subclass_parser.py:
--------------------------------------------------------------------------------
1 | import inspect
2 | from pluginmanager import util
3 | from pluginmanager.iplugin import IPlugin
4 |
5 |
6 | class SubclassParser(object):
7 | def __init__(self, klass=IPlugin):
8 | self.klass = tuple(util.return_list(klass))
9 |
10 | def __call__(self, plugins, *args):
11 | result = []
12 | for plugin in plugins:
13 | if inspect.isclass(plugin) and issubclass(plugin, self.klass):
14 | result.append(plugin)
15 | return result
16 |
--------------------------------------------------------------------------------
/pluginmanager/module_manager.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import logging
4 | import inspect
5 | from .compat import load_source
6 |
7 | from pluginmanager import util
8 |
9 | logging.basicConfig()
10 |
11 |
12 | class ModuleManager(object):
13 | """
14 | `ModuleManager` manages the module plugin filter state and is responsible
15 | for both loading the modules from source code and collecting the plugins
16 | from each of the modules.
17 |
18 | `ModuleManager` can also optionally manage modules explicitly through
19 | the use of the add/get/set loaded modules methods. The default
20 | implementation is hardwired to use the tracked loaded modules if no
21 | modules are passed into the `collect_plugins` method.
22 | """
23 | def __init__(self, module_plugin_filters=None):
24 | """
25 | `module_plugin_filters` are callable filters. Each filter must take
26 | in a list of plugins and a list of plugin names in the form of:
27 |
28 | ::
29 |
30 | def my_module_plugin_filter(plugins: list, plugin_names: list):
31 | pass
32 |
33 | `module_plugin_filters` should return a list of the plugins and may
34 | be either a single object or an iterable.
35 | """
36 | if module_plugin_filters is None:
37 | module_plugin_filters = []
38 | module_plugin_filters = util.return_list(module_plugin_filters)
39 | self.loaded_modules = set()
40 | self.processed_filepaths = dict()
41 | self.module_plugin_filters = module_plugin_filters
42 | self._log = logging.getLogger(__name__)
43 | self._error_string = 'pluginmanager unable to import {}\n'
44 |
45 | def load_modules(self, filepaths):
46 | """
47 | Loads the modules from their `filepaths`. A filepath may be
48 | a directory filepath if there is an `__init__.py` file in the
49 | directory.
50 |
51 | If a filepath errors, the exception will be caught and logged
52 | in the logger.
53 |
54 | Returns a list of modules.
55 | """
56 | # removes filepaths from processed if they are not in sys.modules
57 | self._update_loaded_modules()
58 | filepaths = util.return_set(filepaths)
59 |
60 | modules = []
61 | for filepath in filepaths:
62 | filepath = self._clean_filepath(filepath)
63 | # check to see if already processed and move onto next if so
64 | if self._processed_filepath(filepath):
65 | continue
66 |
67 | module_name = util.get_module_name(filepath)
68 | plugin_module_name = util.create_unique_module_name(module_name)
69 |
70 | try:
71 | module = load_source(plugin_module_name, filepath)
72 | # Catch all exceptions b/c loader will return errors
73 | # within the code itself, such as Syntax, NameErrors, etc.
74 | except Exception:
75 | exc_info = sys.exc_info()
76 | self._log.error(msg=self._error_string.format(filepath),
77 | exc_info=exc_info)
78 | continue
79 |
80 | self.loaded_modules.add(module.__name__)
81 | modules.append(module)
82 | self.processed_filepaths[module.__name__] = filepath
83 |
84 | return modules
85 |
86 | def collect_plugins(self, modules=None):
87 | """
88 | Collects all the plugins from `modules`.
89 | If modules is None, collects the plugins from the loaded modules.
90 |
91 | All plugins are passed through the module filters, if any are any,
92 | and returned as a list.
93 | """
94 | if modules is None:
95 | modules = self.get_loaded_modules()
96 | else:
97 | modules = util.return_list(modules)
98 |
99 | plugins = []
100 | for module in modules:
101 | module_plugins = [(item[1], item[0])
102 | for item
103 | in inspect.getmembers(module)
104 | if item[1] and item[0] != '__builtins__']
105 | module_plugins, names = zip(*module_plugins)
106 |
107 | module_plugins = self._filter_modules(module_plugins, names)
108 | plugins.extend(module_plugins)
109 | return plugins
110 |
111 | def set_module_plugin_filters(self, module_plugin_filters):
112 | """
113 | Sets the internal module filters to `module_plugin_filters`
114 | `module_plugin_filters` may be a single object or an iterable.
115 |
116 | Every module filters must be a callable and take in
117 | a list of plugins and their associated names.
118 | """
119 | module_plugin_filters = util.return_list(module_plugin_filters)
120 | self.module_plugin_filters = module_plugin_filters
121 |
122 | def add_module_plugin_filters(self, module_plugin_filters):
123 | """
124 | Adds `module_plugin_filters` to the internal module filters.
125 | May be a single object or an iterable.
126 |
127 | Every module filters must be a callable and take in
128 | a list of plugins and their associated names.
129 | """
130 | module_plugin_filters = util.return_list(module_plugin_filters)
131 | self.module_plugin_filters.extend(module_plugin_filters)
132 |
133 | def get_module_plugin_filters(self, filter_function=None):
134 | """
135 | Gets the internal module filters. Returns a list object.
136 |
137 | If supplied, the `filter_function` should take in a single
138 | list argument and return back a list. `filter_function` is
139 | designed to given the option for a custom filter on the module filters.
140 | """
141 | if filter_function is None:
142 | return self.module_plugin_filters
143 | else:
144 | return filter_function(self.module_plugin_filters)
145 |
146 | def remove_module_plugin_filters(self, module_plugin_filters):
147 | """
148 | Removes `module_plugin_filters` from the internal module filters.
149 | If the filters are not found in the internal representation,
150 | the function passes on silently.
151 |
152 | `module_plugin_filters` may be a single object or an iterable.
153 | """
154 | util.remove_from_list(self.module_plugin_filters,
155 | module_plugin_filters)
156 |
157 | def _get_modules(self, names):
158 | """
159 | An internal method that gets the `names` from sys.modules and returns
160 | them as a list
161 | """
162 | loaded_modules = []
163 | for name in names:
164 | loaded_modules.append(sys.modules[name])
165 | return loaded_modules
166 |
167 | def add_to_loaded_modules(self, modules):
168 | """
169 | Manually add in `modules` to be tracked by the module manager.
170 |
171 | `modules` may be a single object or an iterable.
172 | """
173 | modules = util.return_set(modules)
174 | for module in modules:
175 | if not isinstance(module, str):
176 | module = module.__name__
177 | self.loaded_modules.add(module)
178 |
179 | def get_loaded_modules(self):
180 | """
181 | Returns all modules loaded by this instance.
182 | """
183 | return self._get_modules(self.loaded_modules)
184 |
185 | def _filter_modules(self, plugins, names):
186 | """
187 | Internal helper method to parse all of the plugins and names
188 | through each of the module filters
189 | """
190 | if self.module_plugin_filters:
191 | # check to make sure the number of plugins isn't changing
192 | original_length_plugins = len(plugins)
193 | module_plugins = set()
194 | for module_filter in self.module_plugin_filters:
195 | module_plugins.update(module_filter(plugins, names))
196 | if len(plugins) < original_length_plugins:
197 | warning = """Module Filter removing plugins from original
198 | data member! Suggest creating a new list in each module
199 | filter and returning new list instead of modifying the
200 | original data member so subsequent module filters can have
201 | access to all the possible plugins.\n {}"""
202 |
203 | self._log.info(warning.format(module_filter))
204 |
205 | plugins = module_plugins
206 | return plugins
207 |
208 | def _clean_filepath(self, filepath):
209 | """
210 | processes the filepath by checking if it is a directory or not
211 | and adding `.py` if not present.
212 | """
213 | if (os.path.isdir(filepath) and
214 | os.path.isfile(os.path.join(filepath, '__init__.py'))):
215 |
216 | filepath = os.path.join(filepath, '__init__.py')
217 |
218 | if (not filepath.endswith('.py') and
219 | os.path.isfile(filepath + '.py')):
220 | filepath += '.py'
221 | return filepath
222 |
223 | def _processed_filepath(self, filepath):
224 | """
225 | checks to see if the filepath has already been processed
226 | """
227 | processed = False
228 | if filepath in self.processed_filepaths.values():
229 | processed = True
230 |
231 | return processed
232 |
233 | def _update_loaded_modules(self):
234 | """
235 | Updates the loaded modules by checking if they are still in sys.modules
236 | """
237 | system_modules = sys.modules.keys()
238 | for module in list(self.loaded_modules):
239 | if module not in system_modules:
240 | self.processed_filepaths.pop(module)
241 | self.loaded_modules.remove(module)
242 |
--------------------------------------------------------------------------------
/pluginmanager/plugin_filters/__init__.py:
--------------------------------------------------------------------------------
1 | from .by_name import NameFilter
2 | from .active import ActiveFilter
3 |
4 | __all__ = ['NameFilter', 'ActiveFilter']
5 |
--------------------------------------------------------------------------------
/pluginmanager/plugin_filters/active.py:
--------------------------------------------------------------------------------
1 | class ActiveFilter(object):
2 | def __init__(self, active=True):
3 | self.active = active
4 |
5 | def __call__(self, plugins):
6 | activated = []
7 | for plugin in plugins:
8 | if hasattr(plugin, 'active') and plugin.active == self.active:
9 | activated.append(plugin)
10 |
11 | return activated
12 |
--------------------------------------------------------------------------------
/pluginmanager/plugin_filters/by_name.py:
--------------------------------------------------------------------------------
1 | from pluginmanager import util
2 |
3 |
4 | class NameFilter(object):
5 | def __init__(self, names=None):
6 | if names is None:
7 | names = []
8 | self.names = util.return_list(names)
9 |
10 | def __call__(self, plugins):
11 | approved_plugins = []
12 | for plugin in plugins:
13 | if hasattr(plugin, 'name') and plugin.name in self.names:
14 | approved_plugins.append(plugin)
15 | return approved_plugins
16 |
--------------------------------------------------------------------------------
/pluginmanager/plugin_interface.py:
--------------------------------------------------------------------------------
1 | from .directory_manager import DirectoryManager
2 | from .file_manager import FileManager
3 | from .module_manager import ModuleManager
4 | from .entry_point_manager import EntryPointManager
5 | from .plugin_manager import PluginManager
6 | from .iplugin import IPlugin
7 |
8 |
9 | class PluginInterface(object):
10 | def __init__(self, **kwargs):
11 |
12 | self.directory_manager = kwargs.get('directory_manager',
13 | DirectoryManager())
14 |
15 | self.file_manager = kwargs.get('file_manager', FileManager())
16 | self.module_manager = kwargs.get('module_manager', ModuleManager())
17 | self.entry_point_manager = kwargs.get('entry_point_manager',
18 | EntryPointManager())
19 |
20 | self.plugin_manager = kwargs.get('plugin_manager', PluginManager())
21 |
22 | def track_site_package_paths(self):
23 | """
24 | A helper method to add all of the site packages tracked by python
25 | to the set of plugin directories.
26 |
27 | NOTE that if using a virtualenv, there is an outstanding bug with the
28 | method used here. While there is a workaround implemented, when using a
29 | virutalenv this method WILL NOT track every single path tracked by
30 | python. See: https://github.com/pypa/virtualenv/issues/355
31 | """
32 | return self.directory_manager.add_site_packages_paths()
33 |
34 | def collect_plugin_directories(self, directories=None):
35 | if directories is None:
36 | directories = self.get_plugin_directories()
37 | # alias for pep8 reasons
38 | dir_manage = self.directory_manager
39 | plugin_directories = dir_manage.collect_directories(directories)
40 | return plugin_directories
41 |
42 | def collect_plugin_filepaths(self, directories=None):
43 | if directories is None:
44 | directories = self.collect_plugin_directories()
45 | plugin_filepaths = self.file_manager.collect_filepaths(directories)
46 | return plugin_filepaths
47 |
48 | def load_modules(self, filepaths=None):
49 | if filepaths is None:
50 | filepaths = self.collect_plugin_filepaths()
51 | loaded_modules = self.module_manager.load_modules(filepaths)
52 | return loaded_modules
53 |
54 | def collect_plugins(self,
55 | modules=None,
56 | store_collected_plugins=True):
57 |
58 | if modules is None:
59 | modules = self.load_modules()
60 | plugins = self.module_manager.collect_plugins(modules)
61 | if store_collected_plugins:
62 | self.add_plugins(plugins)
63 | return plugins
64 |
65 | def collect_entry_point_plugins(self,
66 | entry_point_names=None,
67 | verify_requirements=False,
68 | store_collected_plugins=True,
69 | return_dict=False):
70 |
71 | collect_plugins = self.entry_point_manager.collect_plugins
72 | plugins = collect_plugins(entry_point_names,
73 | verify_requirements,
74 | return_dict)
75 |
76 | if store_collected_plugins:
77 | if return_dict:
78 | self.plugin_manager.plugins.extend(plugins.values())
79 | else:
80 | self.plugin_manager.plugins.extend(plugins)
81 |
82 | return plugins
83 |
84 | def set_plugins(self, plugins):
85 | """
86 | sets plugins to the internal state.
87 | If the instance member `instantiate_classes` in the underlying
88 | member `plugin_manager` is True and the plugins
89 | have class instances in them, attempts to instatiate the classes.
90 | The default is `True`
91 |
92 | This can be checked/changed by:
93 |
94 | `plugin_interface.plugin_manager.instantiate_classes`
95 |
96 | If the instance member `unique_instances` in the underlying member
97 | `plugin_manager` is True and duplicate instances are passed in,
98 | this method will not track the new instances internally.
99 | The default is `True`
100 |
101 | This can be checked/changed by:
102 |
103 | `plugin_interface.plugin_manager.unique_instances`
104 |
105 | """
106 | self.plugin_manager.set_plugins(plugins)
107 |
108 | def add_plugins(self, plugins):
109 | """
110 | Adds plugins to the internal state. `plugins` may be a single
111 | object or an iterable.
112 |
113 | If the instance member `instantiate_classes` in the underlying
114 | member `plugin_manager` is True and the plugins
115 | have class instances in them, attempts to instatiate the classes.
116 | Default is `True`
117 |
118 | This can be checked/changed by:
119 |
120 | `plugin_interface.plugin_manager.instantiate_classes`
121 |
122 | If the instance member `unique_instances` in the underlying member
123 | `plugin_manager` is True and duplicate instances are passed in,
124 | this method will not track the new instances internally.
125 | Default is `True`
126 |
127 | This can be checked/changed by:
128 |
129 | `plugin_interface.plugin_manager.unique_instances`
130 |
131 | """
132 | self.plugin_manager.add_plugins(plugins)
133 |
134 | def remove_plugins(self, plugins):
135 | """
136 | removes `plugins` from the internal state
137 |
138 | `plugins` may be a single object or an iterable.
139 | """
140 | self.plugin_manager.remove_plugins(plugins)
141 |
142 | def get_plugins(self, filter_function=None):
143 | """
144 | Gets out the plugins from the internal state. Returns a list
145 | object.
146 |
147 | If the optional filter_function is supplied, applies the filter
148 | function to the arguments before returning them. Filters should
149 | be callable and take a list argument of plugins.
150 | """
151 | return self.plugin_manager.get_plugins(filter_function)
152 |
153 | def add_plugin_directories(self, paths, except_blacklisted=True):
154 | """
155 | Adds `directories` to the set of plugin directories.
156 |
157 | `directories` may be either a single object or a iterable.
158 |
159 | `directories` can be relative paths, but will be converted into
160 | absolute paths based on the current working directory.
161 |
162 | if `except_blacklisted` is `True` all `directories` in
163 | that are blacklisted will be removed
164 | """
165 | self.directory_manager.add_directories(paths, except_blacklisted)
166 |
167 | def get_plugin_directories(self):
168 | """
169 | Returns the plugin directories in a `set` object
170 | """
171 | return self.directory_manager.get_directories()
172 |
173 | def remove_plugin_directories(self, paths):
174 | """
175 | Removes any `directories` from the set of plugin directories.
176 |
177 | `directories` may be a single object or an iterable.
178 |
179 | Recommend passing in all paths as absolute, but the method will
180 | attemmpt to convert all paths to absolute if they are not already
181 | based on the current working directory.
182 | """
183 | self.directory_manager.remove_directories(paths)
184 |
185 | def set_plugin_directories(self, paths, except_blacklisted=True):
186 | """
187 | Sets the plugin directories to `directories`. This will delete
188 | the previous state stored in `self.plugin_directories` in favor
189 | of the `directories` passed in.
190 |
191 | `directories` may be either a single object or an iterable.
192 |
193 | `directories` can contain relative paths but will be
194 | converted into absolute paths based on the current working
195 | directory.
196 |
197 | if `except_blacklisted` is `True` all `directories` in
198 | blacklisted that are blacklisted will be removed
199 | """
200 | self.directory_manager.set_directories(paths, except_blacklisted)
201 |
202 | def add_entry_points(self, names):
203 | self.entry_point_manager.add_entry_points(names)
204 |
205 | def remove_entry_points(self, names):
206 | self.entry_point_manager.remove_entry_points(names)
207 |
208 | def set_entry_points(self, names):
209 | self.entry_point_manager.set_entry_points(names)
210 |
211 | def get_entry_points(self):
212 | return self.entry_point_manager.get_entry_points()
213 |
214 | def add_plugin_filepaths(self, filepaths, except_blacklisted=True):
215 | """
216 | Adds `filepaths` to internal state. Recommend passing
217 | in absolute filepaths. Method will attempt to convert to
218 | absolute paths if they are not already.
219 |
220 | `filepaths` can be a single object or an iterable
221 |
222 | If `except_blacklisted` is `True`, all `filepaths` that
223 | have been blacklisted will not be added.
224 | """
225 | self.file_manager.add_plugin_filepaths(filepaths,
226 | except_blacklisted)
227 |
228 | def get_plugin_filepaths(self):
229 | """
230 | returns the plugin filepaths tracked internally as a `set` object.
231 | """
232 | return self.file_manager.get_plugin_filepaths()
233 |
234 | def remove_plugin_filepaths(self, filepaths):
235 | """
236 | Removes `filepaths` from internal state.
237 | Recommend passing in absolute filepaths. Method will
238 | attempt to convert to absolute paths if not passed in.
239 |
240 | `filepaths` can be a single object or an iterable.
241 | """
242 | self.file_manager.remove_plugin_filepaths(filepaths)
243 |
244 | def set_plugin_filepaths(self, filepaths, except_blacklisted=True):
245 | """
246 | Sets internal state to `filepaths`. Recommend passing
247 | in absolute filepaths. Method will attempt to convert to
248 | absolute paths if they are not already.
249 |
250 | `filepaths` can be a single object or an iterable.
251 |
252 | If `except_blacklisted` is `True`, all `filepaths` that
253 | have been blacklisted will not be set.
254 | """
255 | self.file_manager.set_plugin_filepaths(filepaths,
256 | except_blacklisted)
257 |
258 | def add_to_loaded_modules(self, modules):
259 | """
260 | Manually add in `modules` to be tracked by the module manager.
261 |
262 | `modules` may be a single object or an iterable.
263 | """
264 | self.module_manager.add_to_loaded_modules(modules)
265 |
266 | def get_loaded_modules(self):
267 | """
268 | Returns all modules loaded by this instance.
269 | """
270 | return self.module_manager.get_loaded_modules()
271 |
272 | def get_instances(self, filter_function=IPlugin):
273 | """
274 | Gets instances out of the internal state using
275 | the default filter supplied in filter_function.
276 | By default, it is the class IPlugin.
277 |
278 | Can optionally pass in a list or tuple of classes
279 | in for `filter_function` which will accomplish
280 | the same goal.
281 |
282 | lastly, a callable can be passed in, however
283 | it is up to the user to determine if the
284 | objects are instances or not.
285 | """
286 | return self.plugin_manager.get_instances(filter_function)
287 |
288 | def add_file_filters(self, file_filters):
289 | """
290 | Adds `file_filters` to the internal file filters.
291 | `file_filters` can be single object or iterable.
292 | """
293 | self.file_manager.add_file_filters(file_filters)
294 |
295 | def get_file_filters(self, filter_function=None):
296 | """
297 | Gets the file filters.
298 | `filter_function`, can be a user defined filter. Should be callable
299 | and return a list.
300 | """
301 | return self.file_manager.get_file_filters(filter_function)
302 |
303 | def remove_file_filters(self, file_filters):
304 | """
305 | Removes the `file_filters` from the internal state.
306 | `file_filters` can be a single object or an iterable.
307 | """
308 | self.file_manager.remove_file_filters(file_filters)
309 |
310 | def set_file_filters(self, file_filters):
311 | """
312 | Sets internal file filters to `file_filters` by tossing old state.
313 | `file_filters` can be single object or iterable.
314 | """
315 | self.file_manager.set_file_filters(file_filters)
316 |
317 | def add_module_plugin_filters(self, module_plugin_filters):
318 | """
319 | Adds `module_plugin_filters` to the internal module filters.
320 | May be a single object or an iterable.
321 |
322 | Every module filters must be a callable and take in
323 | a list of plugins and their associated names.
324 | """
325 | self.module_manager.add_module_plugin_filters(module_plugin_filters)
326 |
327 | def get_module_plugin_filters(self, filter_function=None):
328 | """
329 | Gets the internal module filters. Returns a list object.
330 |
331 | If supplied, the `filter_function` should take in a single
332 | list argument and return back a list. `filter_function` is
333 | designed to given the option for a custom filter on the module filters.
334 | """
335 | return self.module_manager.get_module_plugin_filters(filter_function)
336 |
337 | def remove_module_plugin_filters(self, module_plugin_filters):
338 | """
339 | Removes `module_plugin_filters` from the internal module filters.
340 | If the filters are not found in the internal representation,
341 | the function passes on silently.
342 |
343 | `module_plugin_filters` may be a single object or an iterable.
344 | """
345 | self.module_manager.remove_module_plugin_filters(module_plugin_filters)
346 |
347 | def set_module_plugin_filters(self, module_plugin_filters):
348 | """
349 | Sets the internal module filters to `module_plugin_filters`
350 | `module_plugin_filters` may be a single object or an iterable.
351 |
352 | Every module filters must be a callable and take in
353 | a list of plugins and their associated names.
354 | """
355 | self.module_manager.set_module_plugin_filters(module_plugin_filters)
356 |
357 | def add_blacklisted_directories(self,
358 | directories,
359 | rm_black_dirs_from_stored_dirs=True):
360 | """
361 | Adds `directories` to be blacklisted. Blacklisted directories will not
362 | be returned or searched recursively when calling the
363 | `collect_directories` method.
364 |
365 | `directories` may be a single instance or an iterable. Recommend
366 | passing in absolute paths, but method will try to convert to absolute
367 | paths based on the current working directory.
368 |
369 | If `remove_from_stored_directories` is true, all `directories`
370 | will be removed from internal state.
371 | """
372 | add_black_dirs = self.directory_manager.add_blacklisted_directories
373 | add_black_dirs(directories, rm_black_dirs_from_stored_dirs)
374 |
375 | def get_blacklisted_directories(self):
376 | """
377 | Returns the set of the blacklisted directories.
378 | """
379 | return self.directory_manager.get_blacklisted_directories()
380 |
381 | def set_blacklisted_directories(self,
382 | directories,
383 | rm_black_dirs_from_stored_dirs=True):
384 | """
385 | Sets the `directories` to be blacklisted. Blacklisted directories will
386 | not be returned or searched recursively when calling
387 | `collect_directories`.
388 |
389 | This will replace the previously stored set of blacklisted
390 | paths.
391 |
392 | `directories` may be a single instance or an iterable. Recommend
393 | passing in absolute paths. Method will try to convert to absolute path
394 | based on current working directory.
395 | """
396 | set_black_dirs = self.directory_manager.set_blacklisted_directories
397 | set_black_dirs(directories, rm_black_dirs_from_stored_dirs)
398 |
399 | def remove_blacklisted_directories(self, directories):
400 | """
401 | Attempts to remove the `directories` from the set of blacklisted
402 | directories. If a particular directory is not found in the set of
403 | blacklisted, method will continue on silently.
404 |
405 | `directories` may be a single instance or an iterable. Recommend
406 | passing in absolute paths. Method will try to convert to an absolute
407 | path if it is not already using the current working directory.
408 | """
409 | self.directory_manager.remove_blacklisted_directories(directories)
410 |
411 | def add_blacklisted_filepaths(self, filepaths, remove_from_stored=True):
412 | """
413 | Add `filepaths` to blacklisted filepaths.
414 | If `remove_from_stored` is `True`, any `filepaths` in
415 | internal state will be automatically removed.
416 | """
417 | self.file_manager.add_blacklisted_filepaths(filepaths,
418 | remove_from_stored)
419 |
420 | def get_blacklisted_filepaths(self):
421 | """
422 | Returns the blacklisted filepaths as a set object.
423 | """
424 | return self.file_manager.get_blacklisted_filepaths()
425 |
426 | def set_blacklisted_filepaths(self, filepaths, remove_from_stored=True):
427 | """
428 | Sets internal blacklisted filepaths to filepaths.
429 | If `remove_from_stored` is `True`, any `filepaths` in
430 | internal state will be automatically removed.
431 | """
432 | self.file_manager.set_blacklisted_filepaths(filepaths)
433 |
434 | def remove_blacklisted_filepaths(self, filepaths):
435 | """
436 | Removes `filepaths` from blacklisted filepaths.
437 | `filepaths` may be a single filepath or iterable of filepaths.
438 | recommend passing in absolute filepaths but method will attempt
439 | to convert to absolute filepaths based on current working directory.
440 | """
441 | self.file_manager.remove_blacklisted_filepaths(filepaths)
442 |
443 | def add_blacklisted_plugins(self, plugins):
444 | """
445 | add blacklisted plugins.
446 | `plugins` may be a single object or iterable.
447 | """
448 | self.plugin_manager.add_blacklisted_plugins(plugins)
449 |
450 | def get_blacklisted_plugins(self):
451 | """
452 | gets blacklisted plugins tracked in the internal state
453 | Returns a list object.
454 | """
455 | return self.plugin_manager.get_blacklisted_plugins()
456 |
457 | def set_blacklisted_plugins(self, plugins):
458 | """
459 | sets blacklisted plugins.
460 | `plugins` may be a single object or iterable.
461 | """
462 | self.plugin_manager.set_blacklisted_plugins(plugins)
463 |
464 | def remove_blacklisted_plugins(self, plugins):
465 | """
466 | removes `plugins` from the blacklisted plugins.
467 | `plugins` may be a single object or iterable.
468 | """
469 | self.plugin_manager.remove_blacklisted_plugins(plugins)
470 |
--------------------------------------------------------------------------------
/pluginmanager/plugin_manager.py:
--------------------------------------------------------------------------------
1 | import inspect
2 | from . import util
3 | from .iplugin import IPlugin
4 |
5 |
6 | class PluginManager(object):
7 | """
8 | PluginManager manages the plugin state. It can automatically
9 | instantiate classes and enforce uniqueness, which it does by default.
10 | """
11 | def __init__(self,
12 | unique_instances=True,
13 | instantiate_classes=True,
14 | plugins=None,
15 | blacklisted_plugins=None):
16 | """
17 | `unique_instances` determines if all plugins have to be unique.
18 | This will also ensure that no two instances of the same class are
19 | tracked internally.
20 |
21 | `instantiate_classes` tracks to see if the class should automatically
22 | instantiate class objects that are passed in.
23 | `plugins` can be a single obj or iterable
24 | `blacklisted plugins` can be a single obj or iterable
25 | """
26 | self.unique_instances = unique_instances
27 | self.instantiate_classes = instantiate_classes
28 |
29 | if plugins is None:
30 | plugins = []
31 | if blacklisted_plugins is None:
32 | blacklisted_plugins = []
33 |
34 | self.plugins = util.return_list(plugins)
35 | self.blacklisted_plugins = util.return_list(blacklisted_plugins)
36 |
37 | def get_plugins(self, filter_function=None):
38 | """
39 | Gets out the plugins from the internal state. Returns a list object.
40 | If the optional filter_function is supplied, applies the filter
41 | function to the arguments before returning them. Filters should
42 | be callable and take a list argument of plugins.
43 | """
44 | plugins = self.plugins
45 | if filter_function is not None:
46 | plugins = filter_function(plugins)
47 | return plugins
48 |
49 | def add_plugins(self, plugins):
50 | """
51 | Adds plugins to the internal state. `plugins` may be a single object
52 | or an iterable.
53 |
54 | If `instantiate_classes` is True and the plugins
55 | have class instances in them, attempts to instatiate the classes.
56 |
57 | If `unique_instances` is True and duplicate instances are passed in,
58 | this method will not track the new instances internally.
59 | """
60 | self._instance_parser(plugins)
61 |
62 | def set_plugins(self, plugins):
63 | """
64 | sets plugins to the internal state. `plugins` may be a single object
65 | or an iterable.
66 |
67 | If `instatntiate_classes` is True and the plugins
68 | have class instances in them, attempts to instatiate the classes.
69 |
70 | If `unique_instances` is True and duplicate instances are passed in,
71 | this method will not track the new instances internally.
72 | """
73 | self.plugins = []
74 | self._instance_parser(plugins)
75 |
76 | def remove_plugins(self, plugins):
77 | """
78 | removes `plugins` from the internal state
79 |
80 | `plugins` may be a single object or an iterable.
81 | """
82 | util.remove_from_list(self.plugins, plugins)
83 |
84 | def remove_instance(self, instances):
85 | """
86 | removes `instances` from the internal state.
87 |
88 | Note that this method is syntatic sugar for the
89 | `remove_plugins` acts as a passthrough for that
90 | function.
91 | `instances` may be a single object or an iterable
92 | """
93 | self.remove_plugins(instances)
94 |
95 | def _get_instance(self, klasses):
96 | """
97 | internal method that gets every instance of the klasses
98 | out of the internal plugin state.
99 | """
100 | return [x for x in self.plugins if isinstance(x, klasses)]
101 |
102 | def get_instances(self, filter_function=IPlugin):
103 | """
104 | Gets instances out of the internal state using
105 | the default filter supplied in filter_function.
106 | By default, it is the class IPlugin.
107 |
108 | Can optionally pass in a list or tuple of classes
109 | in for `filter_function` which will accomplish
110 | the same goal.
111 |
112 | lastly, a callable can be passed in, however
113 | it is up to the user to determine if the
114 | objects are instances or not.
115 | """
116 | if isinstance(filter_function, (list, tuple)):
117 | return self._get_instance(filter_function)
118 | elif inspect.isclass(filter_function):
119 | return self._get_instance(filter_function)
120 | elif filter_function is None:
121 | return self.plugins
122 | else:
123 | return filter_function(self.plugins)
124 |
125 | def register_classes(self, classes):
126 | """
127 | Register classes as plugins that are not subclassed from
128 | IPlugin.
129 | `classes` may be a single object or an iterable.
130 | """
131 | classes = util.return_list(classes)
132 | for klass in classes:
133 | IPlugin.register(klass)
134 |
135 | def _instance_parser(self, plugins):
136 | """
137 | internal method to parse instances of plugins.
138 |
139 | Determines if each class is a class instance or
140 | object instance and calls the appropiate handler
141 | method.
142 | """
143 | plugins = util.return_list(plugins)
144 | for instance in plugins:
145 | if inspect.isclass(instance):
146 | self._handle_class_instance(instance)
147 | else:
148 | self._handle_object_instance(instance)
149 |
150 | def _handle_class_instance(self, klass):
151 | """
152 | handles class instances. If a class is blacklisted, returns.
153 | If uniuqe_instances is True and the class is unique, instantiates
154 | the class and adds the new object to plugins.
155 |
156 | If not unique_instances, creates and adds new instance to plugin
157 | state
158 | """
159 | if (klass in self.blacklisted_plugins or not
160 | self.instantiate_classes or
161 | klass == IPlugin):
162 | return
163 | elif self.unique_instances and self._unique_class(klass):
164 | self.plugins.append(klass())
165 | elif not self.unique_instances:
166 | self.plugins.append(klass())
167 |
168 | def _handle_object_instance(self, instance):
169 | klass = type(instance)
170 |
171 | if klass in self.blacklisted_plugins:
172 | return
173 | elif self.unique_instances:
174 | if self._unique_class(klass):
175 | self.plugins.append(instance)
176 | else:
177 | return
178 | else:
179 | self.plugins.append(instance)
180 |
181 | def activate_plugins(self):
182 | """
183 | helper method that attempts to activate plugins
184 | checks to see if plugin has method call before
185 | calling it.
186 | """
187 | for instance in self.get_instances():
188 | if hasattr(instance, 'activate'):
189 | instance.activate()
190 |
191 | def deactivate_plugins(self):
192 | """
193 | helper method that attempts to deactivate plugins.
194 | checks to see if plugin has method call before
195 | calling it.
196 | """
197 | for instance in self.get_instances():
198 | if hasattr(instance, 'deactivate'):
199 | instance.deactivate()
200 |
201 | def _unique_class(self, cls):
202 | """
203 | internal method to check if any of the plugins are instances
204 | of a given cls
205 | """
206 | return not any(isinstance(obj, cls) for obj in self.plugins)
207 |
208 | def add_blacklisted_plugins(self, plugins):
209 | """
210 | add blacklisted plugins.
211 | `plugins` may be a single object or iterable.
212 | """
213 | plugins = util.return_list(plugins)
214 | self.blacklisted_plugins.extend(plugins)
215 |
216 | def set_blacklisted_plugins(self, plugins):
217 | """
218 | sets blacklisted plugins.
219 | `plugins` may be a single object or iterable.
220 | """
221 | plugins = util.return_list(plugins)
222 | self.blacklisted_plugins = plugins
223 |
224 | def get_blacklisted_plugins(self):
225 | """
226 | gets blacklisted plugins tracked in the internal state
227 | Returns a list object.
228 | """
229 | return self.blacklisted_plugins
230 |
231 | def remove_blacklisted_plugins(self, plugins):
232 | """
233 | removes `plugins` from the blacklisted plugins.
234 | `plugins` may be a single object or iterable.
235 | """
236 | util.remove_from_list(self.blacklisted_plugins, plugins)
237 |
--------------------------------------------------------------------------------
/pluginmanager/util.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 |
4 |
5 | def to_absolute_paths(paths):
6 | """
7 | helper method to change `paths` to absolute paths.
8 | Returns a `set` object
9 | `paths` can be either a single object or iterable
10 | """
11 | abspath = os.path.abspath
12 | paths = return_set(paths)
13 | absolute_paths = {abspath(x) for x in paths}
14 | return absolute_paths
15 |
16 |
17 | def get_module_name(filepath):
18 | if filepath.endswith('__init__.py'):
19 | name = os.path.basename(os.path.dirname(filepath))
20 | else:
21 | name = os.path.splitext(os.path.basename(filepath))[0]
22 | return name
23 |
24 |
25 | def remove_from_list(list, remove_items):
26 | list = return_list(list)
27 | remove_items = return_list(remove_items)
28 | for remove in remove_items:
29 | if remove in list:
30 | list.remove(remove)
31 |
32 | return list
33 |
34 |
35 | def remove_from_set(set, remove_items):
36 | set = return_set(set)
37 | remove_items = return_set(remove_items)
38 | for item in remove_items:
39 | if item in set:
40 | set.remove(item)
41 |
42 | return set
43 |
44 |
45 | def create_unique_module_name(plugin_info_or_name):
46 | # get name
47 | # check to see if dict, else assume filepath
48 | if isinstance(plugin_info_or_name, dict):
49 | name = plugin_info_or_name['name']
50 | else:
51 | name = plugin_info_or_name
52 |
53 | module_template = 'pluginmanager_plugin_{}'.format(name)
54 | module_template += '_{number}'
55 | number = 0
56 | while True:
57 | module_name = module_template.format(number=number)
58 | if module_name not in sys.modules:
59 | break
60 | number += 1
61 |
62 | return module_name
63 |
64 |
65 | def get_filepaths_from_dir(dir_path):
66 | filepaths = []
67 | for filename in os.listdir(dir_path):
68 | filepath = os.path.join(dir_path, filename)
69 | if os.path.isfile(filepath):
70 | filepaths.append(filepath)
71 | return filepaths
72 |
73 |
74 | def return_list(object):
75 | if isinstance(object, set):
76 | return list(object)
77 | elif isinstance(object, tuple):
78 | return list(object)
79 | elif not isinstance(object, list):
80 | return [object]
81 | else:
82 | return object
83 |
84 |
85 | def return_set(object):
86 | if isinstance(object, set):
87 | return object
88 | elif isinstance(object, (list, tuple)):
89 | return set(object)
90 | else:
91 | return set([object])
92 |
--------------------------------------------------------------------------------
/requirements-dev.txt:
--------------------------------------------------------------------------------
1 | flake8
2 | sphinx
3 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [bdist_wheel]
2 | universal=1
3 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import os
2 | import shutil
3 | from setuptools import find_packages, setup
4 |
5 |
6 | directory = os.path.abspath(os.path.dirname(__file__))
7 | readme = os.path.join(directory, 'docs', 'source', 'index.rst')
8 |
9 | # FIXME: catch exact exception instead of base exception class
10 | # NOTE: this fixes error found when running `python setup.py develop` in other projects
11 | try:
12 | with open(os.path.join(directory, 'README.rst')) as f:
13 | long_description = f.read()
14 | except Exception:
15 | long_description = ''
16 |
17 | egg_dir = os.path.join(directory, 'pluginmanager.egg-info')
18 | if os.path.isdir(egg_dir):
19 | shutil.rmtree(egg_dir)
20 |
21 | setup(
22 | name="pluginmanager",
23 | version='0.4.1',
24 | description='Python Plugin Management, simplified',
25 | long_description=long_description,
26 | author='Ben Hoff',
27 | author_email='beohoff@gmail.com',
28 | url='https://github.com/benhoff/pluginmanager',
29 | license='GPL3',
30 | classifiers=[
31 | 'Development Status :: 3 - Alpha',
32 | 'Intended Audience :: Developers',
33 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
34 | 'Programming Language :: Python :: 2',
35 | 'Programming Language :: Python :: 2.7',
36 | 'Programming Language :: Python :: 3',
37 | 'Programming Language :: Python :: 3.3',
38 | 'Programming Language :: Python :: 3.4',
39 | 'Programming Language :: Python :: 3.5',
40 | 'Programming Language :: Python :: Implementation :: PyPy',
41 | 'Topic :: Software Development :: Libraries :: Python Modules',
42 | 'Topic :: Utilities',
43 | 'Operating System :: OS Independent'],
44 | keywords='plugin manager framework architecture',
45 | packages= find_packages(exclude=['docs', '*tests', 'test*']),
46 |
47 | extras_require={
48 | 'dev': ['flake8', 'sphinx']
49 | },
50 | )
51 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/benhoff/pluginmanager/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/tests/__init__.py
--------------------------------------------------------------------------------
/tests/compat.py:
--------------------------------------------------------------------------------
1 | from pluginmanager.compat import is_py2
2 | import tempfile
3 |
4 |
5 | if is_py2:
6 | # need to backport `tempfile.TemporaryDirectory`
7 | import shutil as _shutil
8 | import warnings as _warnings
9 | from tempfile import mkdtemp
10 | from ConfigParser import ConfigParser
11 |
12 | def read_dict(self, dictionary, source=''):
13 | elements_added = set()
14 | for section, keys in dictionary.items():
15 | section = str(section)
16 | try:
17 | self.add_section(section)
18 | except:
19 | pass
20 | elements_added.add(section)
21 | for key, value in keys.items():
22 | key = self.optionxform(str(key))
23 | if value is not None:
24 | value = str(value)
25 | elements_added.add((section, key))
26 | self.set(section, key, value)
27 | ConfigParser.read_dict = read_dict
28 | FILE_ERROR = OSError
29 |
30 | class TemporaryDirectory(object):
31 | """Create and return a temporary directory. This has the same
32 | behavior as mkdtemp but can be used as a context manager. For
33 | example:
34 |
35 | with TemporaryDirectory() as tmpdir:
36 | ...
37 |
38 | Upon exiting the context, the directory and everything contained
39 | in it are removed.
40 | """
41 |
42 | def __init__(self, suffix='', prefix="tmp", dir=None):
43 | self.name = mkdtemp(suffix, prefix, dir)
44 |
45 | @classmethod
46 | def _cleanup(cls, name, warn_message):
47 | _shutil.rmtree(name)
48 | _warnings.warn(warn_message)
49 |
50 | def __repr__(self):
51 | return "<{} {!r}>".format(self.__class__.__name__, self.name)
52 |
53 | def __enter__(self):
54 | return self.name
55 |
56 | def __del__(self):
57 | try:
58 | self._cleanup(self.name,
59 | warn_message="Implicitly cleaning up {!r}".format(self)) # noqa
60 | except (OSError, NameError):
61 | pass
62 |
63 | def __exit__(self, exc, value, tb):
64 | self.cleanup()
65 |
66 | def cleanup(self):
67 | _shutil.rmtree(self.name)
68 |
69 | tempfile.TemporaryDirectory = TemporaryDirectory
70 |
--------------------------------------------------------------------------------
/tests/test_directory_manager.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from .compat import tempfile
3 | from pluginmanager.directory_manager import DirectoryManager
4 |
5 |
6 | class TestDirectoryManager(unittest.TestCase):
7 | def setUp(self):
8 | """
9 | create the directory manager as well as
10 | a temp directory and a nested temporary directory inside
11 | of the temp directory
12 | """
13 | self.directory_manager = DirectoryManager()
14 | self.temp_dir = tempfile.TemporaryDirectory()
15 | self.nested_dir = tempfile.TemporaryDirectory(dir=self.temp_dir.name)
16 |
17 | def tearDown(self):
18 | """
19 | clean up the two created temporary directories
20 | """
21 | self.nested_dir.cleanup()
22 | self.temp_dir.cleanup()
23 |
24 | def test_add_directory(self):
25 | """
26 | Add the dir `self.temp_dir` and then check to make sure
27 | it is in the `plugin_directories`
28 | """
29 | self.directory_manager.add_directories(self.temp_dir.name)
30 | self.assertIn(self.temp_dir.name,
31 | self.directory_manager.plugin_directories)
32 |
33 | def test_set_directory(self):
34 | """
35 | Add in the `temp_dir` and then set the `nested_dir`.
36 | Assert that the `nested_dir` is in the `plugin_directories`
37 | and assert that the `temp_dir` is not.
38 | """
39 | self.directory_manager.add_directories(self.temp_dir.name)
40 | self.directory_manager.set_directories(self.nested_dir.name)
41 | self.assertIn(self.nested_dir.name,
42 | self.directory_manager.plugin_directories)
43 |
44 | self.assertNotIn(self.temp_dir.name,
45 | self.directory_manager.plugin_directories)
46 |
47 | def test_set_directories_except_blacklisted(self):
48 | """
49 | add `temp_dir` to the blacklisted dirs and then try
50 | to set it. Assert that `temp_dir` is not in the plugin directories.
51 |
52 | Then, change `except_blacklisted` to false and set the blacklisted dir.
53 | Assert that it is in the plugin directories.
54 | """
55 | self.directory_manager.add_blacklisted_directories(self.temp_dir.name)
56 | self.directory_manager.set_directories(self.temp_dir.name)
57 | self.assertNotIn(self.temp_dir.name,
58 | self.directory_manager.plugin_directories)
59 |
60 | self.directory_manager.set_directories(self.temp_dir.name,
61 | except_blacklisted=False)
62 |
63 | self.assertIn(self.temp_dir.name,
64 | self.directory_manager.plugin_directories)
65 |
66 | def test_add_directories_except_blacklisted(self):
67 | """
68 | add `temp_dir` to the blacklisted dirs and then try
69 | to add it. Assert that `temp_dir` is not in the plugin directories.
70 |
71 | Then, change `except_blacklisted` to false and add in the blacklisted
72 | dir.
73 |
74 | Assert that it is in the plugin directories.
75 | """
76 | self.directory_manager.add_blacklisted_directories(self.temp_dir.name)
77 | self.directory_manager.add_directories(self.temp_dir.name)
78 | self.assertNotIn(self.temp_dir.name,
79 | self.directory_manager.plugin_directories)
80 |
81 | self.directory_manager.add_directories(self.temp_dir.name,
82 | except_blacklisted=False)
83 |
84 | self.assertIn(self.temp_dir.name,
85 | self.directory_manager.plugin_directories)
86 |
87 | def test_add_site_packages(self):
88 | self.directory_manager.add_site_packages_paths()
89 | self.assertEqual(len(self.directory_manager.plugin_directories), 1)
90 |
91 | def test_remove_directories(self):
92 | """
93 | Add in and then remove a directory. Assert that the directory has
94 | been removed.
95 | """
96 | self.directory_manager.add_directories(self.temp_dir.name)
97 | self.assertIn(self.temp_dir.name,
98 | self.directory_manager.plugin_directories)
99 |
100 | self.directory_manager.remove_directories(self.temp_dir.name)
101 | self.assertNotIn(self.temp_dir.name,
102 | self.directory_manager.plugin_directories)
103 |
104 | def test_collect_directories_with_recursion(self):
105 | """
106 | collect directories from `temp_dir`, which has a nested
107 | directory in it. Make sure the nested dir is collected,
108 | the return type is a `set` and that only those two dirs
109 | are returned.
110 | """
111 | dir_manager = self.directory_manager
112 | directories = dir_manager.collect_directories(self.temp_dir.name)
113 | self.assertIn(self.temp_dir.name, directories)
114 | self.assertIn(self.nested_dir.name, directories)
115 | self.assertEqual(len(directories), 2)
116 | self.assertTrue(isinstance(directories, set))
117 |
118 | def test_set_blacklisted_directories(self):
119 | """
120 | Need to check that the `remove_from_stored_directories` arg is working.
121 | Add the temp dir to the plugin directories first before setting the
122 | blacklisted dirs to be equal to `temp_dir`. Check to see if
123 | `blacklisted_directories` contains `temp_dir` and then check to see
124 | that temp_dir is not in `plugin_directories`.
125 | """
126 | self.directory_manager.add_directories(self.temp_dir.name)
127 | self.directory_manager.set_blacklisted_directories(self.temp_dir.name)
128 | self.assertIn(self.temp_dir.name,
129 | self.directory_manager.blacklisted_directories)
130 |
131 | self.assertNotIn(self.temp_dir.name,
132 | self.directory_manager.plugin_directories)
133 |
134 | self.directory_manager.blacklisted_directories = set()
135 | self.directory_manager.add_directories(self.temp_dir.name)
136 | self.directory_manager.set_blacklisted_directories(self.temp_dir.name,
137 | False)
138 |
139 | self.assertIn(self.temp_dir.name,
140 | self.directory_manager.plugin_directories)
141 |
142 | def test_add_blacklisted_directories(self):
143 | """
144 | Need to check that the `remove_from_stored_directories` arg is working.
145 | Add the temp dir to the plugin directories first before adding the
146 | `temp_dir` to blacklisted directories. Check to see if
147 | `blacklisted_directories` contains `temp_dir` and then check to see
148 | that temp_dir is not in `plugin_directories`.
149 | """
150 | self.directory_manager.add_directories(self.temp_dir.name)
151 | self.directory_manager.add_blacklisted_directories(self.temp_dir.name)
152 | self.assertIn(self.temp_dir.name,
153 | self.directory_manager.blacklisted_directories)
154 |
155 | self.assertNotIn(self.temp_dir.name,
156 | self.directory_manager.plugin_directories)
157 |
158 | self.directory_manager.blacklisted_directories = set()
159 | self.directory_manager.add_directories(self.temp_dir.name)
160 | self.directory_manager.add_blacklisted_directories(self.temp_dir.name,
161 | False)
162 |
163 | def test_get_blacklisted_directories(self):
164 | """
165 | check to make sure that blacklisted dirs are a set
166 | """
167 | black_dirs = self.directory_manager.get_blacklisted_directories()
168 | self.assertTrue(isinstance(black_dirs, set))
169 | self.assertEqual(len(black_dirs), 0)
170 |
171 | def test_collect_directories_not_recursive(self):
172 | """
173 | collect directories from `temp_dir`, which has a nested
174 | directory in it. Make sure the nested dir is NOT collected,
175 | the return type is a `set` and that only one directory is
176 | returned.
177 | """
178 | self.directory_manager.recursive = False
179 | dir_manager = self.directory_manager
180 | directories = dir_manager.collect_directories(self.temp_dir.name)
181 | self.assertIn(self.temp_dir.name, directories)
182 | self.assertEqual(len(directories), 1)
183 | self.assertTrue(isinstance(directories, set))
184 |
185 | def test_collect_directories_with_blacklisted_dir(self):
186 | """
187 | add in the `nested_dir` to the blacklisted directories.
188 | Collect the directories with recursion on and make sure that
189 | the `nested_dir` is not collected.
190 | """
191 | dir_manager = self.directory_manager
192 | dir_manager.add_blacklisted_directories(self.nested_dir.name)
193 | directories = dir_manager.collect_directories(self.temp_dir.name)
194 | self.assertNotIn(self.nested_dir.name, directories)
195 | self.assertIn(self.temp_dir.name, directories)
196 |
197 |
198 | if __name__ == '__main__':
199 | unittest.main()
200 |
--------------------------------------------------------------------------------
/tests/test_entry_point_manager.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import setuptools
3 | from pluginmanager.entry_point_manager import EntryPointManager
4 |
5 |
6 | class TestEntryPointManager(unittest.TestCase):
7 | def setUp(self):
8 | self.manager = EntryPointManager()
9 |
10 | def test_add_entry_point(self):
11 | """
12 | add a string using the prescribed method and then
13 | make sure it is in the correct data member
14 | """
15 | test = 'test'
16 | self.manager.add_entry_points(test)
17 | self.assertIn(test, self.manager.entry_point_names)
18 |
19 | def test_set_entry_points(self):
20 | """
21 | add some previous state and then use the prescribed
22 | method to set the state. Check to make sure the previous state
23 | is not there and that the new state is.
24 | """
25 | previous_state = 'previous'
26 | self.manager.add_entry_points(previous_state)
27 | new_state = 'test'
28 | self.manager.set_entry_points(new_state)
29 | entry_points = self.manager.get_entry_points()
30 |
31 | self.assertNotIn(previous_state, entry_points)
32 | self.assertIn(new_state, entry_points)
33 |
34 | def test_remove_entry_points(self):
35 | """
36 | add a string to the entry points and then remove it using the
37 | prescribed method. Make sure that the string is not still there.
38 | """
39 | removed = 'test'
40 | self.manager.add_entry_points(removed)
41 | self.assertIn(removed, self.manager.entry_point_names)
42 | self.manager.remove_entry_points(removed)
43 | self.assertNotIn(removed, self.manager.entry_point_names)
44 |
45 | def test_collect_plugins(self, verify=False):
46 | entry_points = 'distutils.commands'
47 | plugins, _ = self.manager.collect_plugins(entry_points, verify)
48 | self.assertIn(setuptools.command.install.install, plugins)
49 |
50 | def test_collect_plugins_verify_true(self):
51 | self.test_collect_plugins(True)
52 |
53 |
54 | if __name__ == '__main__':
55 | unittest.main()
56 |
--------------------------------------------------------------------------------
/tests/test_file_filters/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/benhoff/pluginmanager/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/tests/test_file_filters/__init__.py
--------------------------------------------------------------------------------
/tests/test_file_filters/test_filenames.py:
--------------------------------------------------------------------------------
1 | import os
2 | import unittest
3 | from pluginmanager.file_filters import FilenameFileFilter
4 |
5 |
6 | class TestFilenameFileGetter(unittest.TestCase):
7 | def setUp(self):
8 | self.file_filter = FilenameFileFilter()
9 |
10 | def test_plugin_valid(self):
11 | filename = self.file_filter.filenames[0]
12 | filename = os.path.join('test/dir', filename)
13 | bad_filename = os.path.join('test/dir/bad.py')
14 | self.assertTrue(self.file_filter.plugin_valid(filename))
15 | self.assertFalse(self.file_filter.plugin_valid(bad_filename))
16 |
17 | def test_call(self):
18 | filepaths = ['valid/path/__init__.py', 'unvalid/dir/blue.py']
19 | filtered = self.file_filter(filepaths)
20 | self.assertIn(filepaths[0], filtered)
21 | self.assertNotIn(filepaths[1], filtered)
22 |
--------------------------------------------------------------------------------
/tests/test_file_filters/test_matching_regex.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import re
3 | from pluginmanager.file_filters import MatchingRegexFileFilter
4 |
5 |
6 | class TestMatchingRegexFileGetter(unittest.TestCase):
7 | def setUp(self):
8 | self.file_filter = MatchingRegexFileFilter(re.compile('plugin*'))
9 |
10 | def test_add_regex(self):
11 | self.file_filter.add_regex_expressions('blue')
12 | self.assertIn('blue', self.file_filter.regex_expressions)
13 |
14 | def test_set_regex(self):
15 | previous = self.file_filter.regex_expressions
16 | self.file_filter.set_regex_expressions('red')
17 | self.assertIn('red', self.file_filter.regex_expressions)
18 | self.assertNotIn(previous, self.file_filter.regex_expressions)
19 |
20 | def test_call(self):
21 | paths = ['fancy/plugin_blue.py', 'test/dir/blah.py']
22 | filtered = self.file_filter(paths)
23 | self.assertIn(paths[0], filtered)
24 | self.assertNotIn(paths[1], filtered)
25 |
26 | def test_plugin_valid(self):
27 | valid_name = 'my/fancy/plugin_blue.py'
28 | unvalid_name = 'plugin/fancy/path/but_not.py'
29 | valid_name = self.file_filter.plugin_valid(valid_name)
30 | unvalid_name = self.file_filter.plugin_valid(unvalid_name)
31 | self.assertTrue(valid_name)
32 | self.assertFalse(unvalid_name)
33 |
--------------------------------------------------------------------------------
/tests/test_file_filters/test_with_info_file.py:
--------------------------------------------------------------------------------
1 | import os
2 | import unittest
3 | from pluginmanager import util
4 | from pluginmanager.file_filters import WithInfoFileFilter
5 | from tests.compat import tempfile
6 | from pluginmanager.compat import FILE_ERROR, ConfigParser
7 |
8 |
9 | class TestWithInfoFileGetter(unittest.TestCase):
10 | def setUp(self):
11 | self.file_filter = WithInfoFileFilter()
12 | self._plugin_file_name = 'plugin.{}'
13 | self.tempdir = tempfile.TemporaryDirectory()
14 | file_template = os.path.join(self.tempdir.name,
15 | self._plugin_file_name)
16 |
17 | open(file_template.format('py'), 'a').close()
18 | p = self._plugin_file_name[:-3]
19 | yapsy_contents = """[Core]\nName = Test\nModule = {}\n""".format(p)
20 |
21 | plugin_file = open(file_template.format('yapsy-plugin'), 'w+')
22 | plugin_file.write(yapsy_contents)
23 | plugin_file.close()
24 | self.plugin_filepaths = util.get_filepaths_from_dir(self.tempdir.name)
25 |
26 | def tearDown(self):
27 | self.tempdir.cleanup()
28 |
29 | def test_callable(self):
30 | filepaths = self.file_filter(self.plugin_filepaths)
31 | valid = False
32 | for filepath in filepaths:
33 | if os.path.basename(filepath) == 'plugin.py':
34 | valid = True
35 | break
36 | self.assertTrue(valid)
37 |
38 | def test_set_file_extension(self):
39 | test_extension = 'test'
40 | self.file_filter.set_file_extensions(test_extension)
41 | self.assertIn(test_extension, self.file_filter.extensions)
42 |
43 | def test_add_file_extensions(self):
44 | new_extension = 'test'
45 | previous_extension = self.file_filter.extensions[0]
46 | self.file_filter.add_file_extensions(new_extension)
47 | self.assertIn(new_extension, self.file_filter.extensions)
48 | self.assertIn(previous_extension, self.file_filter.extensions)
49 |
50 | def test_plugin_valid(self):
51 | valid_filepath = 'file.yapsy-plugin'
52 | unvalid_filepath = 'file.bad'
53 | valid_filepath = self.file_filter.plugin_valid(valid_filepath)
54 | unvalid_filepath = self.file_filter.plugin_valid(unvalid_filepath)
55 | self.assertTrue(valid_filepath)
56 | self.assertFalse(unvalid_filepath)
57 |
58 | def test_get_plugin_info(self):
59 | plugin_infos = self.file_filter.get_plugin_infos(self.plugin_filepaths)
60 | plugin_infos = plugin_infos.pop()
61 | self.assertIn('name', plugin_infos)
62 | self.assertEqual(plugin_infos['name'], 'Test')
63 |
64 | def test_get_plugin_filepath(self):
65 | f = self.file_filter.get_plugin_filepaths
66 | plugin_filepaths = f(self.plugin_filepaths)
67 | file_name = self._plugin_file_name.format('py')
68 | python_file = os.path.basename(plugin_filepaths.pop())
69 | self.assertEqual(file_name, python_file)
70 |
71 | def test_parse_config_details(self):
72 | base, dir_name = os.path.split(self.tempdir.name)
73 | config = ConfigParser()
74 | config.read_dict({"Core": {"Module": base, "Name": 'blah'}})
75 | dir_path = os.path.join(base, '__init__.py')
76 | if os.path.isfile(dir_path):
77 | os.remove(dir_path)
78 |
79 | self.assertRaises(FILE_ERROR,
80 | self.file_filter._parse_config_details,
81 | config,
82 | base)
83 | open(dir_path, 'a').close()
84 | config.read_dict({"Core": {"Module": base, "Name": 'test'}})
85 | config = self.file_filter._parse_config_details(config, base)
86 | self.assertTrue(config['path'] == dir_path)
87 |
88 | def test_empty_dirs(self):
89 | with tempfile.TemporaryDirectory() as temp_dir:
90 | info, filepaths = self.file_filter.get_info_and_filepaths(temp_dir)
91 | self.assertEqual(info, [])
92 | self.assertEqual(filepaths, set())
93 |
--------------------------------------------------------------------------------
/tests/test_file_manager.py:
--------------------------------------------------------------------------------
1 | import os
2 | import unittest
3 | from .compat import tempfile
4 | from pluginmanager.file_manager import FileManager
5 |
6 |
7 | class TestFileManager(unittest.TestCase):
8 | def setUp(self):
9 | """
10 | Create the file manager, a temporary directory, and
11 | two empty files cleverly named `one.py` and `two.py`
12 | """
13 | self.file_manager = FileManager()
14 | self.temp_dir = tempfile.TemporaryDirectory()
15 |
16 | file_path_template = os.path.join(self.temp_dir.name, '{}.py')
17 | self.filepath_one = file_path_template.format('one')
18 | self.filepath_two = file_path_template.format('two')
19 | open(self.filepath_one, 'a+').close()
20 | open(self.filepath_two, 'a+').close()
21 |
22 | def tearDown(self):
23 | """
24 | clean up the temporary directory
25 | """
26 | self.temp_dir.cleanup()
27 |
28 | def test_collect_filepaths(self):
29 | """
30 | pass in the temporary directory in to the `collect_filepaths` method
31 | and then check to see if the filepaths created in the `setUp` function
32 | are present in the collected filepaths
33 | """
34 | filepaths = self.file_manager.collect_filepaths(self.temp_dir.name)
35 | self.assertIn(self.filepath_one, filepaths)
36 | self.assertIn(self.filepath_two, filepaths)
37 |
38 | def test_collect_filepaths_with_blacklisted_filepath(self):
39 | """
40 | add filepath_one to the blacklisted filepaths and then
41 | collect the filepaths and verify that filepath_one is NOT
42 | in the collected filepaths, but filepath_two is.
43 | """
44 | self.file_manager.add_blacklisted_filepaths(self.filepath_one)
45 | filepaths = self.file_manager.collect_filepaths(self.temp_dir.name)
46 | self.assertIn(self.filepath_two, filepaths)
47 | self.assertNotIn(self.filepath_one, filepaths)
48 |
49 | def test_add_plugin_filepaths(self):
50 | """
51 | Wnat to test the `except_blacklisted` arg to this method,
52 | so start off by adding a blacklisted filepath. Then add in
53 | both the blacklisted filepath and a non blacklisted filepath
54 | using the method call. Check to make sure that the blacklisted filepath
55 | is NOT added and that the normal filepath is. Then use the override
56 | method to add in the blacklisted file and see that it is tracked
57 | internally.
58 | """
59 | self.file_manager.add_blacklisted_filepaths(self.filepath_two)
60 | filepaths = [self.filepath_one, self.filepath_two]
61 | self.file_manager.add_plugin_filepaths(filepaths)
62 | self.assertIn(self.filepath_one, self.file_manager.plugin_filepaths)
63 | self.assertNotIn(self.filepath_two, self.file_manager.plugin_filepaths)
64 |
65 | self.file_manager.add_plugin_filepaths(self.filepath_two,
66 | except_blacklisted=False)
67 |
68 | self.assertIn(self.filepath_two, self.file_manager.plugin_filepaths)
69 |
70 | def test_set_plugin_filepaths(self):
71 | """
72 | Wnat to test the `except_blacklisted` arg to this method,
73 | so start off by adding a blacklisted filepath. Then set the filepaths
74 | to both the blacklisted filepath and a non blacklisted filepath
75 | using the method call. Check to make sure that the blacklisted filepath
76 | is NOT added and that the normal filepath is. Then use the override
77 | argument to set in the blacklisted file and see that it is tracked
78 | internally.
79 | """
80 | self.file_manager.add_blacklisted_filepaths(self.filepath_two)
81 |
82 | filepaths = [self.filepath_one, self.filepath_two]
83 | self.file_manager.set_plugin_filepaths(filepaths)
84 | self.assertIn(self.filepath_one, self.file_manager.plugin_filepaths)
85 | self.assertNotIn(self.filepath_two, self.file_manager.plugin_filepaths)
86 |
87 | self.file_manager.set_plugin_filepaths(self.filepath_two,
88 | except_blacklisted=False)
89 |
90 | self.assertIn(self.filepath_two, self.file_manager.plugin_filepaths)
91 | self.assertNotIn(self.filepath_one, self.file_manager.plugin_filepaths)
92 |
93 | def test_remove_plugin_filepaths(self):
94 | """
95 | Add in a filepath, make sure it's there, remove it, make sure it's not
96 | there.
97 | """
98 | self.file_manager.add_plugin_filepaths(self.filepath_one)
99 | self.assertIn(self.filepath_one, self.file_manager.plugin_filepaths)
100 | self.file_manager.remove_plugin_filepaths(self.filepath_one)
101 | self.assertNotIn(self.filepath_one, self.file_manager.plugin_filepaths)
102 |
103 | def test_get_plugin_filepaths(self):
104 | """
105 | get filepaths, assert that it is a set
106 | """
107 | filepaths = self.file_manager.get_plugin_filepaths()
108 | self.assertTrue(isinstance(filepaths, set))
109 | self.assertEqual(len(filepaths), 0)
110 |
111 | def test_set_file_filters(self):
112 | """
113 | create some old state to overwrite, then set the file filter
114 | to be an object and check to make sure the object is tracked
115 | in state
116 | """
117 | # create old state to be overwritten
118 | old_file_filter_state = object()
119 | self.file_manager.add_file_filters(old_file_filter_state)
120 |
121 | # Create a abstract object for testing
122 | obj = object()
123 | self.file_manager.set_file_filters(obj)
124 | self.assertNotIn(old_file_filter_state, self.file_manager.file_filters)
125 | self.assertIn(obj, self.file_manager.file_filters)
126 |
127 | def test_add_file_filters(self):
128 | """
129 | Create an object, add it to the file filters and assert that
130 | the created object is in the file filters
131 | check first that the file filters are empty
132 | """
133 | test_obj = object()
134 | self.assertEqual(len(self.file_manager.file_filters), 0)
135 | self.file_manager.add_file_filters(test_obj)
136 | self.assertIn(test_obj, self.file_manager.file_filters)
137 |
138 | def test_get_file_filters(self):
139 | """
140 | create two test objects and track them internally.
141 | Using the get method, return the internal state and make sure
142 | both test objects are in the internal state.
143 |
144 | want to test the optional argument `filter_function`.
145 | Therefore create a `test_filter` function and hardcode
146 | it to return one of the created objects.
147 | Pass in the created filter function in and make
148 | sure that it is called correctly.
149 | """
150 | obj_1 = object()
151 | obj_2 = object()
152 | self.file_manager.set_file_filters([obj_1, obj_2])
153 | filters = self.file_manager.get_file_filters()
154 | self.assertIn(obj_1, filters)
155 | self.assertIn(obj_2, filters)
156 |
157 | def test_filter(file_filters):
158 | for f in file_filters:
159 | if f == obj_1:
160 | return [obj_1, ]
161 |
162 | result = self.file_manager.get_file_filters(test_filter)
163 | self.assertIn(obj_1, result)
164 | self.assertNotIn(obj_2, result)
165 |
166 | def test_remove_file_filters(self):
167 | """
168 | track a file filter than remove it. Make sure
169 | the removed filter is no longer tracked internally
170 | """
171 | test_filter = object()
172 | self.file_manager.add_file_filters(test_filter)
173 | self.assertIn(test_filter, self.file_manager.file_filters)
174 |
175 | self.file_manager.remove_file_filters(test_filter)
176 | self.assertNotIn(test_filter, self.file_manager.file_filters)
177 |
178 | def test_add_blacklisted_filepaths(self):
179 | """
180 | Want to check that we remove added blacklisted filepaths from stored
181 | plugin filepaths
182 | So at the start, add in our two filepaths to the internal state.
183 |
184 | assert that blacklisted filepaths are empty, then add a filepath.
185 | Assert that the added filepath is in the internal blacklist state and
186 | that the blacklisted filepath is NOT in the internal plugin filepath
187 | state.
188 |
189 | Next, overide the default arg for `remove_from_stored` to False, and
190 | add another blacklisted filepath. Now assert that the second
191 | blacklisted filepath is still tracked internally for a plugin filepath
192 | and that the blacklisted filepath is tracked as a blacklisted filepath
193 | """
194 | self.file_manager.add_plugin_filepaths([self.filepath_one,
195 | self.filepath_two])
196 |
197 | self.assertEqual(len(self.file_manager.blacklisted_filepaths), 0)
198 | self.file_manager.add_blacklisted_filepaths(self.filepath_one)
199 | self.assertIn(self.filepath_one,
200 | self.file_manager.blacklisted_filepaths)
201 |
202 | self.assertNotIn(self.filepath_one, self.file_manager.plugin_filepaths)
203 |
204 | self.file_manager.add_blacklisted_filepaths(self.filepath_two,
205 | remove_from_stored=False)
206 |
207 | self.assertIn(self.filepath_two,
208 | self.file_manager.blacklisted_filepaths)
209 |
210 | self.assertIn(self.filepath_two,
211 | self.file_manager.plugin_filepaths)
212 |
213 | def test_set_blacklisted_filepaths(self):
214 | """
215 | Want to check that we remove set blacklisted filepaths from stored
216 | plugin filepaths.
217 | So at the start, add in our two filepaths to the internal state.
218 |
219 | assert that blacklisted filepaths are empty, then set a blacklisted
220 | filepath. Assert that the set filepath is in the internal blacklist
221 | state and that the blacklisted filepath is NOT in the internal plugin
222 | filepath state.
223 |
224 | Next, overide the default arg for `remove_from_stored` to False, and
225 | set another blacklisted filepath. Now assert that the second
226 | blacklisted filepath is still tracked internally for a plugin filepath
227 | and that the blacklisted filepath is tracked as a blacklisted filepath
228 | """
229 | self.file_manager.add_plugin_filepaths([self.filepath_one,
230 | self.filepath_two])
231 |
232 | self.assertEqual(len(self.file_manager.blacklisted_filepaths), 0)
233 | self.file_manager.set_blacklisted_filepaths(self.filepath_one)
234 | self.assertIn(self.filepath_one,
235 | self.file_manager.blacklisted_filepaths)
236 |
237 | self.assertNotIn(self.filepath_one, self.file_manager.plugin_filepaths)
238 |
239 | self.file_manager.set_blacklisted_filepaths(self.filepath_two,
240 | remove_from_stored=False)
241 |
242 | self.assertIn(self.filepath_two,
243 | self.file_manager.blacklisted_filepaths)
244 |
245 | self.assertIn(self.filepath_two, self.file_manager.plugin_filepaths)
246 | self.assertNotIn(self.filepath_one,
247 | self.file_manager.blacklisted_filepaths)
248 |
249 | def test_remove_blacklisted_filepaths(self):
250 | """
251 | Add a blacklisted filepath, assert it is in the state.
252 | Then remove it using the method and assert that it is not in the state
253 | """
254 | self.file_manager.add_blacklisted_filepaths(self.filepath_one)
255 | self.assertIn(self.filepath_one,
256 | self.file_manager.blacklisted_filepaths)
257 |
258 | self.file_manager.remove_blacklisted_filepaths(self.filepath_one)
259 | self.assertNotIn(self.filepath_one,
260 | self.file_manager.blacklisted_filepaths)
261 |
262 | def test_get_blacklisted_filepath(self):
263 | """
264 | assert that return is set and is empty. Then add file and assert
265 | that the filepath is in the result and is a set object
266 | """
267 | blacklisted_filepath = self.file_manager.get_blacklisted_filepaths()
268 | self.assertTrue(isinstance(blacklisted_filepath, set))
269 | self.assertEqual(len(blacklisted_filepath), 0)
270 | self.file_manager.add_blacklisted_filepaths(self.filepath_one)
271 |
272 | tracked_filepaths = self.file_manager.get_blacklisted_filepaths()
273 | self.assertTrue(isinstance(tracked_filepaths, set))
274 | self.assertIn(self.filepath_one, tracked_filepaths)
275 |
276 | def test_filter_filepaths(self):
277 | filepaths = ['test/dir', 'dir/test']
278 | no_filter = self.file_manager._filter_filepaths(filepaths)
279 | self.assertEqual(filepaths, no_filter)
280 |
281 | def test_filter(filepaths):
282 | for filepath in filepaths:
283 | if filepath == 'test/dir':
284 | filepath = [filepath]
285 | return filepath
286 |
287 | self.file_manager.add_file_filters(test_filter)
288 | filtered_filepaths = self.file_manager._filter_filepaths(filepaths)
289 | self.assertIn('test/dir', filtered_filepaths)
290 | self.assertNotIn('dir/test', filtered_filepaths)
291 |
292 |
293 | if __name__ == '__main__':
294 | unittest.main()
295 |
--------------------------------------------------------------------------------
/tests/test_filter_integration.py:
--------------------------------------------------------------------------------
1 | import os
2 | import types
3 | import unittest
4 | from .compat import tempfile
5 | import pluginmanager
6 |
7 |
8 | class TestClass(pluginmanager.IPlugin):
9 | def __init__(self):
10 | super(TestClass, self).__init__()
11 |
12 |
13 | class TestIntegration(unittest.TestCase):
14 | def setUp(self):
15 | self.interface = pluginmanager.PluginInterface()
16 |
17 | def test_file_filters(self):
18 | bogus_file = str()
19 | init = str()
20 | blue_file = str()
21 | contains_init = []
22 | contains_blue = []
23 | temp_dir = tempfile.TemporaryDirectory()
24 | dir_name = temp_dir.name
25 | filename_filter = pluginmanager.file_filters.FilenameFileFilter()
26 | self.interface.set_file_filters(filename_filter)
27 | init = os.path.join(dir_name, '__init__.py')
28 | bogus_file = os.path.join(dir_name, 'bogus.py')
29 | blue_file = os.path.join(dir_name, 'blue.py')
30 | open(init, 'a+').close()
31 | open(bogus_file, 'a+').close()
32 | open(blue_file, 'a+').close()
33 | contains_init = self.interface.collect_plugin_filepaths(dir_name)
34 | regex = pluginmanager.file_filters.MatchingRegexFileFilter('blue.py')
35 | self.interface.set_file_filters(regex)
36 | contains_blue = self.interface.collect_plugin_filepaths(dir_name)
37 | temp_dir.cleanup()
38 | self.assertIn(init, contains_init)
39 | self.assertIn(blue_file, contains_blue)
40 | self.assertNotIn(bogus_file, contains_init)
41 | self.assertNotIn(bogus_file, contains_blue)
42 |
43 | def test_module_filters(self):
44 | module = types.ModuleType('test')
45 | module.plugin = pluginmanager.IPlugin
46 | module.test_plugin = TestClass
47 | bogus = 'five'
48 | module.bogus = bogus
49 | subclass_parser = pluginmanager.module_filters.SubclassParser()
50 | self.interface.set_module_plugin_filters(subclass_parser)
51 | contains_plugin = self.interface.collect_plugins(module)
52 | self.assertIn(TestClass, contains_plugin)
53 | self.assertNotIn(bogus, contains_plugin)
54 |
--------------------------------------------------------------------------------
/tests/test_iplugin.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pluginmanager import IPlugin
3 |
4 |
5 | class TestObj:
6 | pass
7 |
8 |
9 | class TestIPlugin(unittest.TestCase):
10 | def setUp(self):
11 | self.plugin = IPlugin()
12 |
13 | def test_active(self):
14 | self.assertFalse(self.plugin.active)
15 |
16 | def test_key_not_in_config(self):
17 | self.plugin.CONFIG_TEMPLATE = {'api_key': None}
18 | self.assertRaises(Exception, self.plugin.check_configuration, {})
19 |
20 | def test_autoname(self):
21 | plugin = IPlugin()
22 | self.assertEqual(plugin.name, "IPlugin")
23 |
24 | def test_activate(self):
25 | self.plugin.activate()
26 | self.assertTrue(self.plugin.active)
27 |
28 | def test_deactivate(self):
29 | self.plugin.deactivate()
30 | self.assertFalse(self.plugin.active)
31 |
32 | def test_check_configuration(self):
33 | self.assertTrue(self.plugin.check_configuration({'shared': None}))
34 |
35 | def test_configure(self):
36 | test_obj = TestObj()
37 | self.plugin.configure(test_obj)
38 | self.assertEqual(self.plugin.configuration, test_obj)
39 |
40 | def test_name(self):
41 | self.assertEqual(self.plugin.name, 'IPlugin')
42 |
43 |
44 | if __name__ == '__main__':
45 | unittest.main()
46 |
--------------------------------------------------------------------------------
/tests/test_module_filters/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/benhoff/pluginmanager/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/tests/test_module_filters/__init__.py
--------------------------------------------------------------------------------
/tests/test_module_filters/test_keyword_parser.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from pluginmanager.module_filters import KeywordParser
4 |
5 |
6 | class TestKeywordParser(unittest.TestCase):
7 | def setUp(self):
8 | self.module_filter = KeywordParser()
9 |
10 | def test_get_plugin(self):
11 | keyword = self.module_filter.keywords[0]
12 | test_obj = type('', (), {})
13 | plugins = [test_obj, 5]
14 | names = [keyword, 'blah']
15 | plugins = self.module_filter(plugins, names)
16 | self.assertIn(test_obj, plugins)
17 | self.assertNotIn(5, plugins)
18 |
--------------------------------------------------------------------------------
/tests/test_module_filters/test_subclass_parser.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pluginmanager import IPlugin
3 | from pluginmanager.module_filters import SubclassParser
4 |
5 |
6 | class Subclass(IPlugin):
7 | pass
8 |
9 |
10 | class TestSubclassParser(unittest.TestCase):
11 | def setUp(self):
12 | self.parser = SubclassParser()
13 |
14 | def test_get_plugins(self):
15 | plugins = [IPlugin(), 4, IPlugin, Subclass]
16 | plugins = self.parser(plugins)
17 | self.assertIn(Subclass, plugins)
18 | self.assertNotIn(4, plugins)
19 |
--------------------------------------------------------------------------------
/tests/test_module_manager.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import types
4 | import logging
5 | import unittest
6 | from .compat import tempfile
7 | from pluginmanager.module_manager import ModuleManager
8 |
9 |
10 | class TestModuleManager(unittest.TestCase):
11 | def setUp(self):
12 | """
13 | create the module manager and a temporary directory.
14 | Write a python file with several data members into
15 | the created temporary directory.
16 | """
17 | self.module_manager = ModuleManager()
18 | self.temp_dir = tempfile.TemporaryDirectory()
19 | self.code_filepath = os.path.join(self.temp_dir.name, "mod_test.py")
20 | code = 'PLUGINS = [5,4]\nfive = 5.0\ndef func():\n\tpass'
21 | with open(self.code_filepath, 'w+') as f:
22 | f.write(code)
23 |
24 | def tearDown(self):
25 | """
26 | cleanup the temporary directory created in the setUp method.
27 | """
28 | self.temp_dir.cleanup()
29 |
30 | def test_load_modules(self):
31 | """
32 | Create some test code. write it into the test code filepath.
33 | Then load the test code. Assert that the test code has all
34 | the desired attributes. Assert that the filepath is in the processed
35 | filepaths and that the expected module name is in the processed
36 | filepaths and the loaded modules.
37 | """
38 | module = self.module_manager.load_modules(self.code_filepath).pop()
39 | self.assertTrue(hasattr(module, 'PLUGINS'))
40 | self.assertTrue(hasattr(module, 'func'))
41 | self.assertTrue(hasattr(module, 'five'))
42 | self.assertEqual(module.PLUGINS, [5, 4])
43 | self.assertEqual(module.five, 5.0)
44 | del sys.modules[module.__name__]
45 | del module
46 | expected_module_name = 'pluginmanager_plugin_mod_test_0'
47 | self.assertIn(expected_module_name, self.module_manager.loaded_modules)
48 | self.assertIn(self.code_filepath,
49 | self.module_manager.processed_filepaths.values())
50 |
51 | self.assertIn(expected_module_name,
52 | self.module_manager.processed_filepaths.keys())
53 |
54 | def test_load_modules_with_processed_filepath(self):
55 | """
56 | add a filepath to the processed filepaths and then assert that
57 | the loaded modules are empty.
58 | """
59 | self.module_manager.processed_filepaths['test'] = self.code_filepath
60 | modules = self.module_manager.load_modules(self.code_filepath)
61 | self.assertEqual(len(modules), 0)
62 |
63 | def test_collect_plugins(self):
64 | """
65 | Create a module with a data member `blue`
66 | collect the plugins from the module and assert that the data member
67 | is present in the collected plugins. Next, collect the plugins without
68 | passing in an argument and assert it's empty. Lastly, add the module to
69 | the loaded modules and collect plugins without passing in anything
70 | explicitly into the method call. Assert that blue is still present in
71 | the collected modules.
72 | """
73 | module_name = 'test_pluginmanager_module'
74 | module = types.ModuleType(module_name)
75 | blue = 'blue data member'
76 | module.blue = blue
77 | plugins = self.module_manager.collect_plugins(module)
78 | self.assertIn(blue, plugins)
79 |
80 | empty_plugins = self.module_manager.collect_plugins()
81 | self.assertEqual(len(empty_plugins), 0)
82 |
83 | self.module_manager.add_to_loaded_modules(module)
84 | sys.modules[module_name] = module
85 | loaded_module_plugins = self.module_manager.collect_plugins()
86 | self.assertIn(blue, loaded_module_plugins)
87 | del sys.modules[module_name]
88 |
89 | def test_set_module_plugin_filters(self):
90 | """
91 | create and add some state in the module filters. Then set the module
92 | filters with a test object. assert that the test object is in the
93 | module filters and that the previous state is not.
94 | """
95 | previous_module = object()
96 | self.module_manager.add_module_plugin_filters(previous_module)
97 | test_obj = object()
98 | self.module_manager.set_module_plugin_filters(test_obj)
99 | self.assertIn(test_obj, self.module_manager.module_plugin_filters)
100 | self.assertNotIn(previous_module,
101 | self.module_manager.module_plugin_filters)
102 |
103 | def test_add_to_loaded_modules(self):
104 | """
105 | assert that the module `types` is not being tracked. Then add the
106 | actual module to the loaded modules and assert that the string name
107 | is there.
108 | Also want to test the string handeling, so pass in a test string and
109 | assert that it is in tracked.
110 | """
111 | types_module_str = 'types'
112 | self.assertNotIn(types_module_str, self.module_manager.loaded_modules)
113 | self.module_manager.add_to_loaded_modules(types)
114 | self.assertIn(types_module_str, self.module_manager.loaded_modules)
115 |
116 | test_module_name = 'bogus'
117 | self.assertNotIn(test_module_name, self.module_manager.loaded_modules)
118 | self.module_manager.add_to_loaded_modules(test_module_name)
119 | self.assertIn(test_module_name, self.module_manager.loaded_modules)
120 |
121 | def test_get_loaded_modules(self):
122 | """
123 | get out the loaded modules. Assert that it is a list and is
124 | empty. Assert that the module `types` is not present. Then add
125 | the module `types` to tracked internally. get the loaded modules
126 | again and assert that the module `types` is present.
127 | """
128 | default_modules = self.module_manager.get_loaded_modules()
129 | self.assertTrue(isinstance(default_modules, list))
130 | self.assertEqual(len(default_modules), 0)
131 |
132 | self.assertNotIn(types, default_modules)
133 | self.module_manager.add_to_loaded_modules(types)
134 | gotten_modules = self.module_manager.get_loaded_modules()
135 | self.assertIn(types, gotten_modules)
136 |
137 | def test_add_module_plugin_filter(self):
138 | """
139 | add a test object to the module filters and assert that it is in there.
140 | """
141 | test_obj = object()
142 | self.module_manager.add_module_plugin_filters(test_obj)
143 | self.assertIn(test_obj, self.module_manager.module_plugin_filters)
144 |
145 | def test_get_module_plugin_filters(self):
146 | """
147 | Assert that the module plugin filters are empty at first. Add an
148 | object. Use the method to get all of the plugin filters out. Assert
149 | that the object returned from the method is a set. That it only has
150 | one object, and that the one object was the object added.
151 | """
152 | self.assertEqual(len(self.module_manager.get_module_plugin_filters()),
153 | 0)
154 |
155 | test_obj = object()
156 | self.module_manager.add_module_plugin_filters(test_obj)
157 | gotten_filters = self.module_manager.get_module_plugin_filters()
158 | self.assertTrue(isinstance(gotten_filters, list))
159 | self.assertEqual(len(gotten_filters), 1)
160 | self.assertIn(test_obj, gotten_filters)
161 |
162 | def test_get_module_plugin_filters_with_filter(self):
163 | """
164 | want to test the ability to add filter functions to
165 | the ascribed method so create two objects and add them
166 | both to the module plugin filters. Create a function that
167 | returns only one of the objects and pass the funciton in
168 | to the method call. Assert that the expected object is
169 | in the list, while the other is not.
170 | """
171 | test_obj_1 = object()
172 | test_obj_2 = object()
173 | objects = [test_obj_1, test_obj_2]
174 | self.module_manager.add_module_plugin_filters(objects)
175 |
176 | def get_obj_1_filter(filters):
177 | for filter_ in filters:
178 | if filter_ == test_obj_1:
179 | return [test_obj_1, ]
180 |
181 | get_filters = self.module_manager.get_module_plugin_filters
182 | filters = get_filters(get_obj_1_filter)
183 | self.assertIn(test_obj_1, filters)
184 | self.assertNotIn(test_obj_2, filters)
185 | self.assertIn(test_obj_2, self.module_manager.module_plugin_filters)
186 |
187 | def test_remove_module_plugin_filters(self):
188 | """
189 | create an object, add it to the module plugin filters. Assert that the
190 | object is there. call the method to remove the object. Assert that it
191 | is not there.
192 | """
193 | test_obj = object()
194 | self.module_manager.add_module_plugin_filters(test_obj)
195 | self.assertIn(test_obj, self.module_manager.module_plugin_filters)
196 | self.module_manager.remove_module_plugin_filters(test_obj)
197 | self.assertNotIn(test_obj, self.module_manager.module_plugin_filters)
198 |
199 | def test_load_failing_module(self):
200 | """
201 | This tests that a failing import does not stop the program
202 | Currently, logging is disabled to prevent noise in the logs.
203 | Should change it to expect the log. Should.
204 | """
205 | logging.disable(logging.CRITICAL)
206 | filepath = os.path.join(self.temp_dir.name, 'fail.py')
207 | with open(filepath, 'w+') as f:
208 | f.write('blue=5/nred=')
209 | self.module_manager.load_modules(filepath)
210 | logging.disable(logging.NOTSET)
211 |
212 | def test_filter_modules(self):
213 | """
214 | Create a filter that returns only instances of floats. Create a list
215 | of plugins that include both a float and a non-float member.
216 | pass the list through the filter function and assert that the float
217 | member made it, while the non float member did not.
218 | """
219 | def filter_(plugins, *args):
220 | result = []
221 | for plugin in plugins:
222 | if isinstance(plugin, float):
223 | result.append(plugin)
224 | return result
225 | self.module_manager.add_module_plugin_filters(filter_)
226 | instance = object()
227 | plugins = [5.0, instance]
228 | filtered = self.module_manager._filter_modules(plugins, [])
229 | self.assertNotIn(instance, filtered)
230 | self.assertIn(5.0, filtered)
231 |
232 | def bad_filter(plugins, *args):
233 | for plugin in plugins:
234 | if not isinstance(plugin, float):
235 | plugins.remove(plugin)
236 | return plugins
237 |
238 | self.module_manager.set_module_plugin_filters(bad_filter)
239 | self.module_manager._filter_modules(plugins, [])
240 |
241 | def test_processed_filepath(self):
242 | """
243 | Create two fake filepaths, a "processed" filepath and an
244 | unprocessed filepath. Set the processed filepath in the internal
245 | data memeber `processed_filepaths`. Then test the prescribed method,
246 | asserting that the processed filepath returns a True, while the
247 | unprocessed filepath correctly returns a False
248 | """
249 | processed_filepath = 'dir/processed'
250 | test_filepath = 'dir/test'
251 | self.module_manager.processed_filepaths['test'] = processed_filepath
252 | # test processed_filepath
253 | processed = self.module_manager._processed_filepath(processed_filepath)
254 | self.assertTrue(processed)
255 | # test regular dir
256 | unprocessed = self.module_manager._processed_filepath(test_filepath)
257 | self.assertFalse(unprocessed)
258 |
259 | def test_clean_filepath(self):
260 | """
261 | Create an `__init__.py` file in the temp dir. Pass the temp dir
262 | filepath into the prescribed method and assert that the returned
263 | filepath is the created `__init__.py` file in the temp dir.
264 |
265 | Next, pull off the extension information from the file and repass the
266 | filepath in, asserting that it correctly reappends the expected
267 | extension.
268 | """
269 | expected_filepath = os.path.join(self.temp_dir.name, '__init__.py')
270 | open(expected_filepath, 'a+').close()
271 | cleaned_file = self.module_manager._clean_filepath(self.temp_dir.name)
272 | self.assertEqual(cleaned_file, expected_filepath)
273 | no_ext = expected_filepath[:-3]
274 | processed_ext = self.module_manager._clean_filepath(no_ext)
275 | self.assertEqual(processed_ext, expected_filepath)
276 |
277 | def test_update_loaded_modules(self):
278 | """
279 | Add the filepath created in setup to the processed filepath with the
280 | name `module_name`. Also add the `module_name` to sys.modules
281 | """
282 | module_name = 'test_pluginmanager'
283 | self.module_manager.loaded_modules.add(module_name)
284 | processed_filepaths = self.module_manager.processed_filepaths
285 | processed_filepaths[module_name] = self.code_filepath
286 | sys.modules[module_name] = None
287 | self.module_manager._update_loaded_modules()
288 | self.assertIn(module_name, self.module_manager.loaded_modules)
289 | self.assertIn(module_name, processed_filepaths.keys())
290 | del sys.modules[module_name]
291 | self.module_manager._update_loaded_modules()
292 | self.assertNotIn(module_name, processed_filepaths.keys())
293 | self.assertNotIn(module_name, self.module_manager.loaded_modules)
294 |
--------------------------------------------------------------------------------
/tests/test_plugin_filters/__init__.py:
--------------------------------------------------------------------------------
1 | class ActiveTestClass(object):
2 | def __init__(self, active=False):
3 | self.active = active
4 |
--------------------------------------------------------------------------------
/tests/test_plugin_filters/test_active.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from . import ActiveTestClass
4 |
5 | from pluginmanager.plugin_filters import ActiveFilter
6 |
7 |
8 | class TestActivated(unittest.TestCase):
9 | def test_activated(self):
10 | deactivated_test = ActiveTestClass()
11 | activated_test = ActiveTestClass(True)
12 | plugins = [deactivated_test, activated_test]
13 | filter_ = ActiveFilter()
14 |
15 | filtered_plugins = filter_(plugins)
16 | self.assertIn(activated_test, filtered_plugins)
17 | self.assertNotIn(deactivated_test, filtered_plugins)
18 |
19 | filter_.active = False
20 |
21 | filtered_plugins = filter_(plugins)
22 | self.assertNotIn(activated_test, filtered_plugins)
23 | self.assertIn(deactivated_test, filtered_plugins)
24 |
--------------------------------------------------------------------------------
/tests/test_plugin_filters/test_by_name.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pluginmanager.plugin_filters import NameFilter
3 |
4 |
5 | class NameClass:
6 | def __init__(self, name='test'):
7 | self.name = name
8 |
9 |
10 | class TestByName(unittest.TestCase):
11 | def test_by_name(self):
12 | test_name = NameClass('test')
13 | bogus_name = NameClass('bogus')
14 | plugins = [test_name, bogus_name]
15 | filter_ = NameFilter('test')
16 | plugins = filter_(plugins)
17 | self.assertIn(test_name, plugins)
18 | self.assertNotIn(bogus_name, plugins)
19 |
--------------------------------------------------------------------------------
/tests/test_plugin_interface.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import types
4 | import unittest
5 | from .compat import tempfile
6 | from pluginmanager.plugin_interface import PluginInterface
7 | from pluginmanager.iplugin import IPlugin
8 |
9 |
10 | class TestInterface(unittest.TestCase):
11 | def setUp(self):
12 | self.test_obj = IPlugin()
13 | self.interface = PluginInterface()
14 |
15 | def test_collect_plugins_no_args(self):
16 | temp_dir = tempfile.TemporaryDirectory()
17 | with open(os.path.join(temp_dir.name, 'a.py'), 'w+') as f:
18 | f.write('import pluginmanager\n')
19 | f.write('class T(pluginmanager.IPlugin):\n')
20 | f.write("\tname='red'\n")
21 | f.write('\tdef __init__(self):\n')
22 | f.write('\t\tsuper(T, self).__init__()')
23 | self.interface.set_plugin_directories(temp_dir.name)
24 | plugin = self.interface.collect_plugins()[0]
25 | self.assertEqual(plugin.name, 'red')
26 | stored_plugin = self.interface.get_instances()[0]
27 | self.assertEqual(stored_plugin.name, 'red')
28 |
29 | temp_dir.cleanup()
30 |
31 | def test_collect_plugins_no_state(self):
32 | temp_dir = tempfile.TemporaryDirectory()
33 | with open(os.path.join(temp_dir.name, 'a.py'), 'w+') as f:
34 | f.write('import pluginmanager\n')
35 | f.write('class T(pluginmanager.IPlugin):\n')
36 | f.write("\tname='red'\n")
37 | f.write('\tdef __init__(self):\n')
38 | f.write('\t\tsuper(T, self).__init__()')
39 | self.interface.set_plugin_directories(temp_dir.name)
40 | plugin = self.interface.collect_plugins(None, False)[0]
41 | self.assertEqual(plugin.name, 'red')
42 | stored_plugins = self.interface.get_plugins()
43 | self.assertEqual(len(stored_plugins), 0)
44 |
45 | temp_dir.cleanup()
46 |
47 |
48 | def test_collect_plugin_directories(self):
49 | dir_names = []
50 | dirs = []
51 | with tempfile.TemporaryDirectory() as main_dir:
52 | self.interface.set_plugin_directories(main_dir)
53 | dir_names.append(main_dir)
54 | with tempfile.TemporaryDirectory(dir=main_dir) as recursive_dir:
55 | dir_names.append(recursive_dir)
56 | dirs = self.interface.collect_plugin_directories(main_dir)
57 | self.assertIn(dir_names[0], dirs)
58 | self.assertIn(dir_names[1], dirs)
59 |
60 | def test_collect_plugin_filepaths(self):
61 | filename = 'test.py'
62 | filepaths = []
63 | with tempfile.TemporaryDirectory() as main_dir:
64 | filename = os.path.join(main_dir, filename)
65 | open(filename, 'a+').close()
66 | filepaths = self.interface.collect_plugin_filepaths(main_dir)
67 | self.assertIn(filename, filepaths)
68 |
69 | def test_load_modules(self):
70 | module = None
71 | with tempfile.NamedTemporaryFile(suffix='.py') as file:
72 | file.write(b'test=1')
73 | file.seek(0)
74 | module = self.interface.load_modules(file.name)
75 | module = module.pop()
76 | self.assertEqual(module.test, 1)
77 |
78 | def test_collect_plugins(self):
79 | module = types.ModuleType('test')
80 | module.test = 5
81 | plugins = self.interface.collect_plugins(module)
82 | self.assertIn(5, plugins)
83 |
84 | def test_track_site_package_path(self):
85 | # TODO: better test method
86 | num_directories = len(self.interface.get_plugin_directories())
87 | self.interface.track_site_package_paths()
88 | new_num_dirs = len(self.interface.get_plugin_directories())
89 | self.assertTrue(new_num_dirs > num_directories)
90 |
91 | def test_plugins(self):
92 | plugin_1 = IPlugin()
93 | plugin_2 = IPlugin()
94 | self.interface.add_plugins([plugin_1])
95 | plugins = self.interface.get_plugins()
96 | self.assertIn(plugin_1, plugins)
97 | self.interface.set_plugins(plugin_2)
98 | set_plugins = self.interface.get_plugins()
99 | self.assertIn(plugin_2, set_plugins)
100 | self.assertNotIn(plugin_1, set_plugins)
101 | self.interface.remove_plugins(plugin_2)
102 | removed_plugins = self.interface.get_plugins()
103 | self.assertNotIn(plugin_2, removed_plugins)
104 |
105 | def test_add_plugin_filepaths(self):
106 | filepath_1 = '/tmp/a.py'
107 | filepath_2 = '/tmp/b.py'
108 | self.interface.add_plugin_filepaths(filepath_1)
109 | filepaths = self.interface.get_plugin_filepaths()
110 | self.assertIn(filepath_1, filepaths)
111 | self.interface.set_plugin_filepaths(filepath_2)
112 | set_filepaths = self.interface.get_plugin_filepaths()
113 | self.assertIn(filepath_2, set_filepaths)
114 | self.assertNotIn(filepath_1, set_filepaths)
115 | self.interface.remove_plugin_filepaths(filepath_2)
116 | removed_filepaths = self.interface.get_plugin_filepaths()
117 | self.assertNotIn(filepath_2, removed_filepaths)
118 |
119 | def test_blacklisted_directories(self):
120 | path_1 = '/tmp/dir_1'
121 | path_2 = '/tmp/dir_2'
122 | self.interface.add_blacklisted_directories(path_1)
123 | stored_paths = self.interface.get_blacklisted_directories()
124 | self.assertIn(path_1, stored_paths)
125 | self.interface.set_blacklisted_directories(path_2)
126 | set_paths = self.interface.get_blacklisted_directories()
127 | self.assertIn(path_2, set_paths)
128 | self.interface.remove_blacklisted_directories(path_2)
129 | rm_paths = self.interface.get_blacklisted_directories()
130 | self.assertNotIn(path_2, rm_paths)
131 |
132 | def test_add_get_set_dirs(self):
133 | dir_1 = '/tmp/dir'
134 | dir_2 = '/tmp/dir_2'
135 | self.interface.add_plugin_directories(dir_1)
136 | dirs = self.interface.get_plugin_directories()
137 | self.assertIn(dir_1, dirs)
138 | self.interface.set_plugin_directories(dir_2)
139 | set_dirs = self.interface.get_plugin_directories()
140 | self.assertIn(dir_2, set_dirs)
141 | self.assertNotIn(dir_1, set_dirs)
142 | self.interface.remove_plugin_directories(dir_2)
143 | removed_dirs = self.interface.get_plugin_directories()
144 | self.assertNotIn(dir_2, removed_dirs)
145 |
146 | def test_set_plugins(self):
147 | self.interface.set_plugins(self.test_obj)
148 | plugins = self.interface.get_plugins()
149 | self.assertIn(self.test_obj, plugins)
150 |
151 | def test_add_get_modules(self):
152 | module_name = 'test_module_type'
153 | test_module = types.ModuleType(module_name)
154 | sys.modules[module_name] = test_module
155 | self.interface.add_to_loaded_modules(test_module)
156 | loaded_modules = self.interface.get_loaded_modules()
157 | self.assertIn(test_module, loaded_modules)
158 |
159 | def test_interface(self):
160 | template = '{}_blacklisted_{}'
161 | methods = ['plugins']
162 |
163 | def get_func(attr):
164 | return getattr(self.interface, attr)
165 |
166 | adders = [get_func(template.format('add',
167 | method)) for method in methods]
168 |
169 | setters = [get_func(template.format('set',
170 | method)) for method in methods]
171 |
172 | getters = [get_func(template.format('get',
173 | method)) for method in methods]
174 |
175 | removers = [get_func(template.format('remove',
176 | method)) for method in methods]
177 | instance = object()
178 | second_instance = object()
179 | for adder, setter, getter, remover in zip(adders, setters,
180 | getters, removers):
181 |
182 | adder(instance)
183 | self.assertIn(instance, getter())
184 | setter(second_instance)
185 | self.assertIn(second_instance, getter())
186 | self.assertNotIn(instance, getter())
187 | remover(second_instance)
188 | self.assertNotIn(second_instance, getter())
189 | """
190 | def test_add_plugin_directories(self):
191 | added_dir = 'pluginmanager'
192 | self.interface.add_plugin_directories(added_dir)
193 | directories = self.interface.get_plugin_directories()
194 | self.assertIn(added_dir, directories)
195 |
196 | def test_set_plugin_directories(self):
197 | preset_dir = self.interface.get_plugin_directories().pop()
198 | set_dir = 'pluginmanager'
199 | self.interface.set_plugin_directories(set_dir)
200 | directories = self.interface.get_plugin_directories()
201 | self.assertIn(set_dir, directories)
202 | self.assertNotIn(preset_dir, directories)
203 | """
204 |
205 | def test_set_blacklist_filepath(self):
206 | filepath = '/test/dir'
207 | self.interface.set_blacklisted_filepaths(filepath)
208 | blacklisted = self.interface.get_blacklisted_filepaths()
209 | self.assertIn(filepath, blacklisted)
210 |
211 | def test_test_interface(self):
212 | # all methods in interface follow this pattern
213 | template = '{}_{}_filters'
214 | # currently the only two filters supported are file and module
215 | filters = ['file', 'module_plugin']
216 | # set up a function to get the actual method calls
217 | get_func = lambda attr: getattr(self.interface, attr) # flake8: noqa
218 | # list comprhensions, our function, and filters to get all the methods
219 | adders = [get_func(template.format('add',
220 | filter_)) for filter_ in filters]
221 |
222 | setters = [get_func(template.format('set',
223 | filter_)) for filter_ in filters]
224 |
225 | getters = [get_func(template.format('get',
226 | filter_)) for filter_ in filters]
227 |
228 | removers = [get_func(template.format('remove',
229 | filter_)) for filter_ in filters]
230 | instance = object()
231 | second_instance = object()
232 | for adder, setter, getter, remover in zip(adders, setters,
233 | getters, removers):
234 |
235 | adder(instance)
236 | self.assertIn(instance, getter())
237 | setter(second_instance)
238 | self.assertIn(second_instance, getter())
239 | self.assertNotIn(instance, getter())
240 | remover(second_instance)
241 | self.assertNotIn(second_instance, getter())
242 |
--------------------------------------------------------------------------------
/tests/test_plugin_manager.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pluginmanager import PluginManager, IPlugin
3 |
4 |
5 | class InstanceClass(IPlugin):
6 | def __init__(self, active=False):
7 | super(InstanceClass, self).__init__()
8 |
9 |
10 | def _test_filter(plugins):
11 | result = []
12 | for plugin in plugins:
13 | if hasattr(plugin, 'name') and plugin.name == 'red':
14 | result.append(plugin)
15 | return result
16 |
17 |
18 | class TestPluginManager(unittest.TestCase):
19 | def setUp(self):
20 | self.instance = InstanceClass()
21 | self.plugin_manager = PluginManager()
22 | self.plugin_manager.add_plugins(self.instance)
23 |
24 | def test_add_instances(self):
25 | self.plugin_manager.unique_instances = False
26 | instance = InstanceClass()
27 | self.plugin_manager.add_plugins(instance)
28 | instances = self.plugin_manager.get_plugins()
29 | self.assertIn(instance, instances)
30 | self.plugin_manager.add_plugins(InstanceClass())
31 | instances = self.plugin_manager.get_plugins()
32 | self.assertTrue(len(instances) > 2)
33 | uniq = self.plugin_manager._unique_class(InstanceClass)
34 | self.assertFalse(uniq)
35 |
36 | def test_register_class(self):
37 | class TestClass:
38 | pass
39 |
40 | self.assertFalse(issubclass(TestClass, IPlugin))
41 | self.plugin_manager.register_classes(TestClass)
42 | self.assertTrue(issubclass(TestClass, IPlugin))
43 |
44 | def test_class_in_blacklist(self):
45 | self.plugin_manager.set_plugins([])
46 | self.plugin_manager.add_blacklisted_plugins(InstanceClass)
47 | self.plugin_manager._handle_object_instance(self.instance)
48 | plugins = self.plugin_manager.get_plugins()
49 | self.assertEqual(plugins, [])
50 |
51 | def test_blacklist_plugins(self):
52 | self.plugin_manager.add_blacklisted_plugins(InstanceClass)
53 | blacklisted = self.plugin_manager.get_blacklisted_plugins()
54 | self.assertIn(InstanceClass, blacklisted)
55 |
56 | def test_handle_classs_instance(self):
57 | self.plugin_manager.instantiate_classes = False
58 | is_none = self.plugin_manager._handle_class_instance(5)
59 | self.assertIsNone(is_none)
60 |
61 | def test_class_instance_not_unique(self):
62 | self.plugin_manager.unique_instances = False
63 | num_plugins = len(self.plugin_manager.plugins)
64 | self.plugin_manager._handle_class_instance(InstanceClass)
65 | self.assertTrue(len(self.plugin_manager.plugins) > num_plugins)
66 |
67 | def test_class_instance_unique(self):
68 | num_plugins = len(self.plugin_manager.plugins)
69 | self.plugin_manager.unique_instances = True
70 | self.plugin_manager._handle_class_instance(InstanceClass)
71 | self.assertTrue(len(self.plugin_manager.plugins) == num_plugins)
72 |
73 | def test_get_plugins(self):
74 | self.plugin_manager.unique_instances = False
75 | instance_2 = InstanceClass()
76 | instance_2.name = 'red'
77 | self.plugin_manager.add_plugins(instance_2)
78 |
79 | filtered_plugins = self.plugin_manager.get_plugins(_test_filter)
80 | self.assertNotIn(self.instance, filtered_plugins)
81 | self.assertIn(instance_2, filtered_plugins)
82 |
83 | def test_set_plugins(self):
84 | instance_2 = InstanceClass()
85 | self.plugin_manager.set_plugins(instance_2)
86 | plugins = self.plugin_manager.get_plugins()
87 | self.assertIn(instance_2, plugins)
88 | self.assertNotIn(self.instance, plugins)
89 |
90 | def test_remove_plugin(self):
91 | self.plugin_manager.remove_plugins(self.instance)
92 | plugins = self.plugin_manager.get_plugins()
93 | self.assertNotIn(self.instance, plugins)
94 |
95 | def test_remove_instance(self):
96 | self.plugin_manager.remove_instance(self.instance)
97 | plugins = self.plugin_manager.get_plugins()
98 | self.assertNotIn(self.instance, plugins)
99 |
100 | def test_get_instances(self):
101 | self.plugin_manager.unique_instances = False
102 | instance_2 = InstanceClass()
103 | instance_2.name = 'red'
104 | self.plugin_manager.add_plugins((instance_2, 5.0))
105 | instances = self.plugin_manager.get_instances((IPlugin, InstanceClass))
106 | self.assertIn(instance_2, instances)
107 | self.assertIn(self.instance, instances)
108 | self.assertNotIn(5.0, instances)
109 | filtered_instances = self.plugin_manager.get_instances(_test_filter)
110 | self.assertIn(instance_2, filtered_instances)
111 | self.assertNotIn(self.instance, filtered_instances)
112 | self.assertNotIn(5.0, filtered_instances)
113 | all_instances = self.plugin_manager.get_instances(None)
114 | self.assertIn(self.instance, all_instances)
115 | self.assertIn(instance_2, all_instances)
116 | self.assertIn(5.0, all_instances)
117 |
118 | def test_activate_instances(self):
119 | self.plugin_manager.activate_plugins()
120 | instances = self.plugin_manager.get_plugins()
121 | self.assertTrue(instances[0].active)
122 |
123 | def test_deactive_instances(self):
124 | instance = InstanceClass(True)
125 | self.plugin_manager.add_plugins(instance)
126 | self.plugin_manager.deactivate_plugins()
127 | instances = self.plugin_manager.get_plugins()
128 | for instance in instances:
129 | self.assertFalse(instance.active)
130 |
--------------------------------------------------------------------------------
/tests/test_util.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import unittest
3 | from pluginmanager import util
4 |
5 |
6 | class TestUtil(unittest.TestCase):
7 | def test_get_module_name(self):
8 | ends_with_init = 'my/dirname/__init__.py'
9 | python_file = 'my/path/test.py'
10 | ends_with_init = util.get_module_name(ends_with_init)
11 | python_file = util.get_module_name(python_file)
12 | self.assertEqual(ends_with_init, 'dirname')
13 | self.assertEqual(python_file, 'test')
14 |
15 | def test_create_unique_module_name(self):
16 | name = 'test'
17 | module_name = util.create_unique_module_name(name)
18 | sys.modules[module_name] = None
19 | second_module_name = util.create_unique_module_name(name)
20 | self.assertNotEqual(module_name, second_module_name)
21 | self.assertEqual(module_name, 'pluginmanager_plugin_test_0')
22 | self.assertEqual(second_module_name, 'pluginmanager_plugin_test_1')
23 |
24 | def test_create_module_name_with_dict(self):
25 | name = {'name': 'test'}
26 | name = util.create_unique_module_name(name)
27 | self.assertEqual(name, 'pluginmanager_plugin_test_0')
28 |
29 | def test_remove_from_set(self):
30 | obj_1 = object()
31 | obj_2 = object()
32 | test_set = set((obj_1, obj_2))
33 | remove_set = set((obj_2,))
34 |
35 | result_set = util.remove_from_set(test_set, remove_set)
36 | self.assertIn(obj_1, result_set)
37 | self.assertNotIn(obj_2, result_set)
38 |
39 | def test_remove_from_list(self):
40 | obj_1 = object()
41 | obj_2 = object()
42 | test_set = [obj_1, obj_2]
43 | remove_set = [obj_2, ]
44 |
45 | result_set = util.remove_from_list(test_set, remove_set)
46 | self.assertIn(obj_1, result_set)
47 | self.assertNotIn(obj_2, result_set)
48 |
49 |
50 | if __name__ == '__main__':
51 | unittest.main()
52 |
--------------------------------------------------------------------------------