python-catalogus_0.1.0.orig/COPYING0000644000000000000000000004310015055656551014026 0ustar00 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see . Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Moe Ghoul, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. python-catalogus_0.1.0.orig/README.md0000644000000000000000000000273715055656551014265 0ustar00# Catalogus A Python library providing classes for name-to-object registry-like support. ## Overview Catalogus provides a simple and extensible registry system that allows you to: - Register objects by name - Retrieve objects by name - Support lazy loading of objects - Maintain type safety with generic support This library was extracted from the Breezy version control system to provide a reusable registry implementation. ## Installation ```bash pip install catalogus ``` ## Quick Start ```python from catalogus import Registry # Create a registry my_registry = Registry() # Register objects directly my_registry.register('item1', some_object) # Register with lazy loading my_registry.register_lazy('item2', 'my.module', 'MyClass') # Retrieve objects obj = my_registry.get('item1') ``` ## Features - **Type-safe**: Full generic type support with TypeVar - **Lazy loading**: Objects can be loaded on-demand from modules - **Flexible registration**: Support for direct objects and lazy imports - **Iterator support**: Iterate over registered items - **Python 3.9+**: Modern Python support ## Development Install development dependencies: ```bash pip install -e .[dev] ``` Run tests: ```bash pytest ``` Format code: ```bash ruff format ``` Check code style: ```bash ruff check mypy catalogus ``` ## License This project is licensed under the GNU General Public License v2 or later (GPLv2+). ## Contributing Contributions are welcome! Please feel free to submit a Pull Request.python-catalogus_0.1.0.orig/catalogus/0000755000000000000000000000000015055656551014757 5ustar00python-catalogus_0.1.0.orig/pyproject.toml0000644000000000000000000000504015055657041015703 0ustar00[build-system] requires = ["setuptools>=61.0", "setuptools_scm[toml]>=6.2"] build-backend = "setuptools.build_meta" [project] name = "catalogus" version = "0.1.0" description = "Classes to provide name-to-object registry-like support" readme = "README.md" requires-python = ">=3.9" license = {text = "GPL-2.0-or-later"} authors = [ {name = "Breezy Developers", email = "breezy-core@googlegroups.com"}, ] maintainers = [ {name = "Breezy Developers", email = "breezy-core@googlegroups.com"}, ] keywords = ["registry", "plugin", "extensibility"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Topic :: Software Development :: Libraries :: Python Modules", ] dependencies = [] [project.optional-dependencies] dev = [ "pytest>=7.0", "pytest-cov>=4.0", "ruff>=0.1.0", "mypy>=1.0", ] [project.urls] "Homepage" = "https://github.com/breezy-team/catalogus" "Bug Tracker" = "https://github.com/breezy-team/catalogus/issues" "Source Code" = "https://github.com/breezy-team/catalogus" [tool.setuptools.packages.find] where = ["."] include = ["catalogus*"] [tool.ruff] line-length = 88 [tool.ruff.lint] select = [ "E", # pycodestyle errors "W", # pycodestyle warnings "F", # pyflakes "I", # isort "UP", # pyupgrade "B", # flake8-bugbear "C4", # flake8-comprehensions "SIM", # flake8-simplify ] ignore = [ "E501", # line too long (handled by formatter) ] [tool.mypy] python_version = "3.9" warn_return_any = true warn_unused_configs = true disallow_untyped_defs = true disallow_any_generics = true check_untyped_defs = true no_implicit_optional = true warn_redundant_casts = true warn_unused_ignores = true warn_no_return = true strict_equality = true [tool.pytest.ini_options] testpaths = ["tests"] python_files = "test_*.py" addopts = "--cov=catalogus --cov-report=term-missing" [tool.coverage.run] source = ["catalogus"] branch = true [tool.coverage.report] exclude_lines = [ "pragma: no cover", "def __repr__", "raise AssertionError", "raise NotImplementedError", "if __name__ == .__main__.:", "if TYPE_CHECKING:", ] python-catalogus_0.1.0.orig/setup.py0000644000000000000000000000007215055657041014501 0ustar00#!/usr/bin/python3 from setuptools import setup setup() python-catalogus_0.1.0.orig/tests/0000755000000000000000000000000015055656551014137 5ustar00python-catalogus_0.1.0.orig/catalogus/__init__.py0000644000000000000000000000155115055656551017072 0ustar00# Copyright (C) 2025 Breezy Developers # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """Classes to provide name-to-object registry-like support.""" __all__ = ["Registry"] from .registry import ( Registry, ) python-catalogus_0.1.0.orig/catalogus/pyutils.py0000644000000000000000000000743715055663316017052 0ustar00# Copyright (C) 2010 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """General Python convenience functions.""" import sys from typing import Any, Optional def get_named_object(module_name: str, member_name: Optional[str] = None) -> Any: """Get the Python object named by a given module and member name. This is usually much more convenient than dealing with ``__import__`` directly:: >>> doc = get_named_object('breezy.pyutils', 'get_named_object.__doc__') >>> doc.splitlines()[0] 'Get the Python object named by a given module and member name.' :param module_name: a module name, as would be found in sys.modules if the module is already imported. It may contain dots. e.g. 'sys' or 'os.path'. :param member_name: (optional) a name of an attribute in that module to return. It may contain dots. e.g. 'MyClass.some_method'. If not given, the named module will be returned instead. :raises: ImportError or AttributeError. """ # We may have just a module name, or a module name and a member name, # and either may contain dots. __import__'s return value is a bit # unintuitive, so we need to take care to always return the object # specified by the full combination of module name + member name. if member_name: # Give __import__ a from_list. It will return the last module in # the dotted module name. attr_chain = member_name.split(".") from_list = attr_chain[:1] obj = __import__(module_name, {}, {}, from_list) for attr in attr_chain: obj = getattr(obj, attr) else: # We're just importing a module, no attributes, so we have no # from_list. __import__ will return the first module in the dotted # module name, so we look up the module from sys.modules. __import__(module_name, globals(), locals(), []) obj = sys.modules[module_name] return obj def calc_parent_name( module_name: str, member_name: Optional[str] = None ) -> tuple[str, Optional[str], str]: """Determine the 'parent' of a given dotted module name and (optional) member name. The idea is that ``getattr(parent_obj, final_attr)`` will equal get_named_object(module_name, member_name). :return: (module_name, member_name, final_attr) tuple. """ # +SKIP is not recognized by python2.4 # Typical use is:: # # >>> parent_mod, parent_member, final_attr = calc_parent_name( # ... module_name, member_name) # doctest: +SKIP # >>> parent_obj = get_named_object(parent_mod, parent_member) # ... # doctest: +SKIP if member_name is not None: split_name = member_name.rsplit(".", 1) if len(split_name) == 1: return (module_name, None, member_name) else: return (module_name, split_name[0], split_name[1]) else: split_name = module_name.rsplit(".", 1) if len(split_name) == 1: raise AssertionError( f"No parent object for top-level module {module_name!r}" ) else: return (split_name[0], None, split_name[1]) python-catalogus_0.1.0.orig/catalogus/registry.py0000644000000000000000000003102215055657041017172 0ustar00# Copyright (C) 2006-2010 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """Classes to provide name-to-object registry-like support.""" from collections.abc import Iterator from typing import ( Any, Callable, Generic, Optional, TypeVar, Union, cast, ) from .pyutils import get_named_object T = TypeVar("T") class _ObjectGetter(Generic[T]): """Maintain a reference to an object, and return the object on request. This is used by Registry to make plain objects function similarly to lazily imported objects. Objects can be any sort of python object (class, function, module, instance, etc) """ __slots__ = ["_obj"] _obj: T def __init__(self, obj: T) -> None: self._obj = obj def get_module(self) -> str: """Get the module the object was loaded from.""" return self._obj.__module__ def get_obj(self) -> T: """Get the object that was saved at creation time.""" return self._obj class _LazyObjectGetter(_ObjectGetter[T]): """Keep a record of a possible object. When requested, load and return it. """ __slots__ = ["_imported", "_member_name", "_module_name"] def __init__(self, module_name: str, member_name: Optional[str]) -> None: self._module_name = module_name self._member_name = member_name self._imported = False super().__init__(None) # type: ignore def get_module(self) -> str: """Get the module the referenced object will be loaded from.""" return self._module_name def get_obj(self) -> T: """Get the referenced object. Upon first request, the object will be imported. Future requests will return the imported object. """ if not self._imported: self._obj = get_named_object(self._module_name, self._member_name) self._imported = True return super().get_obj() def __repr__(self) -> str: return f"<{self.__class__.__module__}.{self.__class__.__name__} object at {id(self):x}, module={self._module_name!r} attribute={self._member_name!r} imported={self._imported!r}>" K = TypeVar("K") V = TypeVar("V") P = TypeVar("P") class Registry(Generic[K, V, P]): """A class that registers objects to a name. There are many places that want to collect related objects and access them by a key. This class is designed to allow registering the mapping from key to object. It goes one step further, and allows registering a name to a hypothetical object which has not been imported yet. It also supports adding additional information at registration time so that decisions can be made without having to import the object (which may be expensive). The functions 'get', 'get_info', and 'get_help' also support a 'default_key' (settable through my_registry.default_key = XXX, XXX must already be registered.) Calling my_registry.get() or my_registry.get(None), will return the entry for the default key. """ def __init__(self) -> None: """Create a new Registry.""" self._default_key: Optional[K] = None self._dict: dict[K, _ObjectGetter[V]] = {} self._aliases: dict[K, K] = {} self._help_dict: dict[ K, Union[Callable[[Registry[K, V, P], Optional[K]], str], str, None] ] = {} self._info_dict: dict[K, Any] = {} def aliases(self) -> dict[K, K]: """Return a set of the format names which are aliases.""" return dict(self._aliases.items()) def alias_map(self) -> dict[K, list[K]]: """Get a map from target names to lists of their aliases. Returns: Dictionary mapping each target key to a list of its aliases. """ ret: dict[K, list[K]] = {} for alias, target in self._aliases.items(): ret.setdefault(target, []).append(alias) return ret def register( self, key: K, obj: V, help: Optional[ Union[str, Callable[["Registry[K, V, P]", Optional[K]], str]] ] = None, info: Optional[P] = None, override_existing: bool = False, ) -> None: """Register a new object to a name. :param key: This is the key to use to request the object later. :param obj: The object to register. :param help: Help text for this entry. This may be a string or a callable. If it is a callable, it should take two parameters (registry, key): this registry and the key that the help was registered under. :param info: More information for this entry. Registry.get_info() can be used to get this information. Registry treats this as an opaque storage location (it is defined by the caller). :param override_existing: Raise KeyErorr if False and something has already been registered for that key. If True, ignore if there is an existing key (always register the new value). """ if not override_existing and key in self._dict: raise KeyError(f"Key {key!r} already registered") self._dict[key] = _ObjectGetter[V](obj) self._add_help_and_info(key, help=help, info=info) def register_lazy( self, key: K, module_name: str, member_name: Optional[str], help: Optional[ Union[str, Callable[["Registry[K, V, P]", Optional[K]], str]] ] = None, info: Optional[P] = None, override_existing: bool = False, ) -> None: """Register a new object to be loaded on request. :param key: This is the key to use to request the object later. :param module_name: The python path to the module. Such as 'os.path'. :param member_name: The member of the module to return. If empty or None, get() will return the module itself. :param help: Help text for this entry. This may be a string or a callable. :param info: More information for this entry. Registry.get_info() can be used to get this information. Registry treats this as an opaque storage location (it is defined by the caller). :param override_existing: If True, replace the existing object with the new one. If False, if there is already something registered with the same key, raise a KeyError """ if not override_existing and key in self._dict: raise KeyError(f"Key {key!r} already registered") self._dict[key] = _LazyObjectGetter[V](module_name, member_name) self._add_help_and_info(key, help=help, info=info) def register_alias(self, key: K, target: K, info: Optional[P] = None) -> None: """Register an alias. :param key: Alias name :param target: Target key name """ if key in self._dict and key not in self._aliases: raise KeyError(f"Key {key!r} already registered and not an alias") self._dict[key] = self._dict[target] self._aliases[key] = target if info is None: info = self._info_dict[target] self._add_help_and_info(key, help=self._help_dict[target], info=info) def _add_help_and_info( self, key: K, help: Optional[ Union[str, Callable[["Registry[K, V, P]", Optional[K]], str]] ] = None, info: Optional[P] = None, ) -> None: """Add the help and information about this key.""" self._help_dict[key] = help self._info_dict[key] = info def get(self, key: Optional[K] = None) -> V: """Return the object register()'ed to the given key. May raise ImportError if the object was registered lazily and there are any problems, or AttributeError if the module does not have the supplied member. :param key: The key to obtain the object for. If no object has been registered to that key, the object registered for self.default_key will be returned instead, if it exists. Otherwise KeyError will be raised. :return: The previously registered object. :raises ImportError: If the object was registered lazily, and there are problems during import. :raises AttributeError: If registered lazily, and the module does not contain the registered member. """ return self._dict[self._get_key_or_default(key)].get_obj() def _get_module(self, key: K) -> str: """Return the module the object will be or was loaded from. :param key: The key to obtain the module for. :return: The name of the module """ return self._dict[key].get_module() def get_prefix(self, fullname: str) -> Optional[tuple[V, str]]: """Return an object whose key is a prefix of the supplied value. :fullname: The name to find a prefix for :return: a tuple of (object, remainder), where the remainder is the portion of the name that did not match the key. """ for key in self.keys(): if fullname.startswith(str(key)): return self.get(key), fullname[len(str(key)) :] return None def _get_key_or_default(self, key: Optional[K] = None) -> K: """Return either 'key' or the default key if key is None.""" if key is not None: return key if self.default_key is None: raise KeyError("Key is None, and no default key is set") else: return cast(K, self.default_key) def get_help(self, key: Optional[K] = None) -> Optional[str]: """Get the help text associated with the given key.""" the_help = self._help_dict[self._get_key_or_default(key)] if callable(the_help): return the_help(self, key) return the_help def get_info(self, key: Optional[K] = None) -> Optional[P]: """Get the extra information associated with the given key.""" return cast(Optional[P], self._info_dict[self._get_key_or_default(key)]) def remove(self, key: K) -> None: """Remove a registered entry. This is mostly for the test suite, but it can be used by others """ del self._dict[key] def __contains__(self, key: K) -> bool: """Check if a key is registered in this registry. Args: key: The key to check for. Returns: True if the key is registered, False otherwise. """ return key in self._dict def __iter__(self) -> Iterator[K]: """Iterate over all registered keys. Returns: Iterator over the registered keys. """ return iter(self._dict) def keys(self) -> list[K]: """Get a list of registered entries.""" return sorted(self._dict.keys()) # type: ignore def iteritems(self) -> Iterator[tuple[K, V]]: """Iterate over (key, object) pairs. Yields: Tuple of (key, resolved_object) for each registered item. """ for key in self._dict: yield key, self._dict[key].get_obj() def items(self) -> list[tuple[K, V]]: """Get a list of (key, object) pairs. Returns: List of (key, resolved_object) tuples for all registered items. """ # We should not use the iteritems() implementation below (see bug # #430510) return [(key, self._dict[key].get_obj()) for key in self.keys()] def _set_default_key(self, key: Optional[K]) -> None: if key is not None and key not in self._dict: raise KeyError(f"No object registered under key {key}.") else: self._default_key = key def _get_default_key(self) -> Optional[K]: return self._default_key default_key = property( _get_default_key, _set_default_key, doc="Current value of the default key. Can be set to any existing key.", ) python-catalogus_0.1.0.orig/tests/test_pyutils.py0000644000000000000000000000531615055656551017266 0ustar00# Copyright (C) 2010 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """Tests for catalogus.pyutils.""" import unittest from catalogus.pyutils import calc_parent_name, get_named_object class TestGetNamedObject(unittest.TestCase): """Tests for get_named_object.""" def test_module_only(self): import sys self.assertIs(sys, get_named_object("sys")) def test_dotted_module(self): import os.path self.assertIs(os.path, get_named_object("os.path")) def test_module_attr(self): self.assertIs(unittest.TestCase, get_named_object("unittest", "TestCase")) def test_dotted_attr(self): self.assertIs( unittest.TestCase.assertEqual, get_named_object("unittest", "TestCase.assertEqual"), ) def test_package(self): # os is a module import os self.assertIs(os, get_named_object("os")) def test_package_attr(self): # os.path is a module import os.path self.assertIs(os.path.join, get_named_object("os.path", "join")) def test_import_error(self): self.assertRaises(ModuleNotFoundError, get_named_object, "NO_SUCH_MODULE") def test_attribute_error(self): self.assertRaises(AttributeError, get_named_object, "sys", "NO_SUCH_ATTR") class TestCalcParent_name(unittest.TestCase): """Tests for calc_parent_name.""" def test_dotted_member(self): self.assertEqual( ("mod_name", "attr1", "attr2"), calc_parent_name("mod_name", "attr1.attr2") ) def test_undotted_member(self): self.assertEqual( ("mod_name", None, "attr1"), calc_parent_name("mod_name", "attr1") ) def test_dotted_module_no_member(self): self.assertEqual(("mod", None, "sub_mod"), calc_parent_name("mod.sub_mod")) def test_undotted_module_no_member(self): with self.assertRaises(AssertionError) as cm: calc_parent_name("mod_name") self.assertEqual( "No parent object for top-level module 'mod_name'", str(cm.exception) ) python-catalogus_0.1.0.orig/tests/test_registry.py0000644000000000000000000003526015055663316017423 0ustar00# Copyright (C) 2006, 2008-2012, 2016 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """Tests for the Registry classes.""" import os import random import string import sys import tempfile import unittest from catalogus import registry from catalogus.registry import Registry class MockOsutils: @staticmethod def rand_chars(length): return "".join(random.choices(string.ascii_lowercase, k=length)) osutils = MockOsutils() class TestRegistry(unittest.TestCase): def register_stuff(self, a_registry): a_registry.register("one", 1) a_registry.register("two", 2) a_registry.register("four", 4) a_registry.register("five", 5) def test_registry(self): a_registry = Registry() self.register_stuff(a_registry) self.assertIsNone(a_registry.default_key) # test get() (self.default_key is None) self.assertRaises(KeyError, a_registry.get) self.assertRaises(KeyError, a_registry.get, None) self.assertEqual(2, a_registry.get("two")) self.assertRaises(KeyError, a_registry.get, "three") # test _set_default_key a_registry.default_key = "five" self.assertEqual(a_registry.default_key, "five") self.assertEqual(5, a_registry.get()) self.assertEqual(5, a_registry.get(None)) # If they ask for a specific entry, they should get KeyError # not the default value. They can always pass None if they prefer self.assertRaises(KeyError, a_registry.get, "six") self.assertRaises(KeyError, a_registry._set_default_key, "six") # test keys() self.assertEqual(["five", "four", "one", "two"], a_registry.keys()) def test_registry_funcs(self): a_registry = Registry() self.register_stuff(a_registry) self.assertIn("one", a_registry) a_registry.remove("one") self.assertNotIn("one", a_registry) self.assertRaises(KeyError, a_registry.get, "one") a_registry.register("one", "one") self.assertEqual(["five", "four", "one", "two"], sorted(a_registry.keys())) self.assertEqual( [("five", 5), ("four", 4), ("one", "one"), ("two", 2)], sorted(a_registry.iteritems()), ) def test_register_override(self): a_registry = Registry() a_registry.register("one", "one") self.assertRaises(KeyError, a_registry.register, "one", "two") self.assertRaises( KeyError, a_registry.register, "one", "two", override_existing=False ) a_registry.register("one", "two", override_existing=True) self.assertEqual("two", a_registry.get("one")) self.assertRaises(KeyError, a_registry.register_lazy, "one", "three", "four") a_registry.register_lazy("one", "module", "member", override_existing=True) def test_registry_help(self): a_registry = Registry() a_registry.register("one", 1, help="help text for one") # We should not have to import the module to return the help # information a_registry.register_lazy( "two", "nonexistent_module", "member", help="help text for two" ) # We should be able to handle a callable to get information help_calls = [] def generic_help(reg, key): help_calls.append(key) return f"generic help for {key}" a_registry.register("three", 3, help=generic_help) a_registry.register_lazy( "four", "nonexistent_module", "member2", help=generic_help ) a_registry.register("five", 5) def help_from_object(reg, key): obj = reg.get(key) return obj.help() class SimpleObj: def help(self): return "this is my help" a_registry.register("six", SimpleObj(), help=help_from_object) self.assertEqual("help text for one", a_registry.get_help("one")) self.assertEqual("help text for two", a_registry.get_help("two")) self.assertEqual("generic help for three", a_registry.get_help("three")) self.assertEqual(["three"], help_calls) self.assertEqual("generic help for four", a_registry.get_help("four")) self.assertEqual(["three", "four"], help_calls) self.assertEqual(None, a_registry.get_help("five")) self.assertEqual("this is my help", a_registry.get_help("six")) self.assertRaises(KeyError, a_registry.get_help, None) self.assertRaises(KeyError, a_registry.get_help, "seven") a_registry.default_key = "one" self.assertEqual("help text for one", a_registry.get_help(None)) self.assertRaises(KeyError, a_registry.get_help, "seven") self.assertEqual( [ ("five", None), ("four", "generic help for four"), ("one", "help text for one"), ("six", "this is my help"), ("three", "generic help for three"), ("two", "help text for two"), ], sorted((key, a_registry.get_help(key)) for key in a_registry), ) # We don't know what order it was called in, but we should get # 2 more calls to three and four self.assertEqual(["four", "four", "three", "three"], sorted(help_calls)) def test_registry_info(self): a_registry = Registry() a_registry.register("one", 1, info="string info") # We should not have to import the module to return the info a_registry.register_lazy("two", "nonexistent_module", "member", info=2) # We should be able to handle a callable to get information a_registry.register("three", 3, info=["a", "list"]) obj = object() a_registry.register_lazy("four", "nonexistent_module", "member2", info=obj) a_registry.register("five", 5) self.assertEqual("string info", a_registry.get_info("one")) self.assertEqual(2, a_registry.get_info("two")) self.assertEqual(["a", "list"], a_registry.get_info("three")) self.assertIs(obj, a_registry.get_info("four")) self.assertIs(None, a_registry.get_info("five")) self.assertRaises(KeyError, a_registry.get_info, None) self.assertRaises(KeyError, a_registry.get_info, "six") a_registry.default_key = "one" self.assertEqual("string info", a_registry.get_info(None)) self.assertRaises(KeyError, a_registry.get_info, "six") self.assertEqual( [ ("five", None), ("four", obj), ("one", "string info"), ("three", ["a", "list"]), ("two", 2), ], sorted((key, a_registry.get_info(key)) for key in a_registry), ) def test_get_prefix(self): my_registry = Registry() http_object = object() sftp_object = object() my_registry.register("http:", http_object) my_registry.register("sftp:", sftp_object) found_object, suffix = my_registry.get_prefix("http://foo/bar") self.assertEqual("//foo/bar", suffix) self.assertIs(http_object, found_object) self.assertIsNot(sftp_object, found_object) found_object, suffix = my_registry.get_prefix("sftp://baz/qux") self.assertEqual("//baz/qux", suffix) self.assertIs(sftp_object, found_object) def test_registry_alias(self): a_registry = Registry() a_registry.register("one", 1, info="string info") a_registry.register_alias("two", "one") a_registry.register_alias("three", "one", info="own info") self.assertEqual(a_registry.get("one"), a_registry.get("two")) self.assertEqual(a_registry.get_help("one"), a_registry.get_help("two")) self.assertEqual(a_registry.get_info("one"), a_registry.get_info("two")) self.assertEqual("own info", a_registry.get_info("three")) self.assertEqual({"two": "one", "three": "one"}, a_registry.aliases()) self.assertEqual( {"one": ["three", "two"]}, {k: sorted(v) for (k, v) in a_registry.alias_map().items()}, ) def test_registry_alias_exists(self): a_registry = Registry() a_registry.register("one", 1, info="string info") a_registry.register("two", 2) self.assertRaises(KeyError, a_registry.register_alias, "one", "one") def test_registry_alias_targetmissing(self): a_registry = Registry() self.assertRaises(KeyError, a_registry.register_alias, "one", "two") class TestRegistryIter(unittest.TestCase): """Test registry iteration behaviors. There are dark corner cases here when the registered objects trigger addition in the iterated registry. """ def setUp(self): super().setUp() # We create a registry with "official" objects and "hidden" # objects. The later represent the side effects that led to bug #277048 # and #430510 _registry = Registry() def register_more(): _registry.register("hidden", None) # Avoid closing over self by binding local variable self.registry = _registry self.registry.register("passive", None) self.registry.register("active", register_more) self.registry.register("passive-too", None) class InvasiveGetter(registry._ObjectGetter): def get_obj(inner_self): # noqa: N805 # Surprise ! Getting a registered object (think lazy loaded # module) register yet another object ! _registry.register("more hidden", None) return inner_self._obj self.registry.register("hacky", None) # We peek under the covers because the alternative is to use lazy # registration and create a module that can reference our test registry # it's too much work for such a corner case -- vila 090916 self.registry._dict["hacky"] = InvasiveGetter(None) def _iter_them(self, iter_func_name): iter_func = getattr(self.registry, iter_func_name, None) self.assertIsNot(None, iter_func) count = 0 for name, func in iter_func(): count += 1 self.assertNotIn(name, ("hidden", "more hidden")) if func is not None: # Using an object register another one as a side effect func() self.assertEqual(4, count) def test_iteritems(self): # the dict is modified during the iteration self.assertRaises(RuntimeError, self._iter_them, "iteritems") def test_items(self): # we should be able to iterate even if one item modify the dict self._iter_them("items") class TestRegistryWithDirs(unittest.TestCase): """Registry tests that require temporary dirs.""" def create_plugin_file(self, contents): """Create a file to be used as a plugin. This is created in a temporary directory, so that we are sure that it doesn't start in the plugin path. """ tmpdir = tempfile.TemporaryDirectory() self.addCleanup(tmpdir.cleanup) plugin_name = f"bzr_plugin_a_{osutils.rand_chars(4)}" with open(os.path.join(tmpdir.name, plugin_name + ".py"), "wb") as f: f.write(contents) return plugin_name, tmpdir.name def create_simple_plugin(self): return self.create_plugin_file( b'object1 = "foo"\n' b"\n\n" b"def function(a,b,c):\n" b" return a,b,c\n" b"\n\n" b"class MyClass(object):\n" b" def __init__(self, a):\n" b" self.a = a\n" b"\n\n" ) def test_lazy_import_registry_foo(self): a_registry = Registry() a_registry.register_lazy("foo", "unittest", "TestCase") a_registry.register_lazy("bar", "sys", "modules") self.assertEqual(unittest.TestCase, a_registry.get("foo")) self.assertEqual(sys.modules, a_registry.get("bar")) def test_lazy_import_registry(self): plugin_name, plugin_path = self.create_simple_plugin() a_registry = Registry() a_registry.register_lazy("obj", plugin_name, "object1") a_registry.register_lazy("function", plugin_name, "function") a_registry.register_lazy("klass", plugin_name, "MyClass") a_registry.register_lazy("module", plugin_name, None) self.assertEqual( ["function", "klass", "module", "obj"], sorted(a_registry.keys()) ) # The plugin should not be loaded until we grab the first object self.assertNotIn(plugin_name, sys.modules) # By default the plugin won't be in the search path self.assertRaises(ImportError, a_registry.get, "obj") sys.path.append(plugin_path) try: obj = a_registry.get("obj") self.assertEqual("foo", obj) self.assertIn(plugin_name, sys.modules) # Now grab another object func = a_registry.get("function") self.assertEqual(plugin_name, func.__module__) self.assertEqual("function", func.__name__) self.assertEqual((1, [], "3"), func(1, [], "3")) # And finally a class klass = a_registry.get("klass") self.assertEqual(plugin_name, klass.__module__) self.assertEqual("MyClass", klass.__name__) inst = klass(1) self.assertIsInstance(inst, klass) self.assertEqual(1, inst.a) module = a_registry.get("module") self.assertIs(obj, module.object1) self.assertIs(func, module.function) self.assertIs(klass, module.MyClass) finally: sys.path.remove(plugin_path) def test_lazy_import_get_module(self): a_registry = Registry() a_registry.register_lazy("obj", "test_registry", "object1") self.assertEqual("test_registry", a_registry._get_module("obj")) def test_normal_get_module(self): class AThing: """Something.""" a_registry = Registry() a_registry.register("obj", AThing()) self.assertEqual("test_registry", a_registry._get_module("obj"))