pax_global_header00006660000000000000000000000064137141503320014511gustar00rootroot0000000000000052 comment=efff0809b7615c3efc1b84edb5c444b528b274c1 colcon-metadata-0.2.5/000077500000000000000000000000001371415033200145505ustar00rootroot00000000000000colcon-metadata-0.2.5/.travis.yml000066400000000000000000000010051371415033200166550ustar00rootroot00000000000000language: python python: "3.5" dist: trusty sudo: true install: - pip install -U setuptools # install_requires - pip install -U git+https://github.com/colcon/colcon-core - pip install -U PyYAML # tests_require - pip install -U flake8-blind-except flake8-builtins flake8-class-newline flake8-comprehensions flake8-deprecated flake8-docstrings flake8-quotes pep8-naming pylint pytest pytest-cov scspell3k script: # invoke pytest - pytest --cov=colcon_metadata --cov-branch notifications: email: false colcon-metadata-0.2.5/LICENSE000066400000000000000000000261361371415033200155650ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. colcon-metadata-0.2.5/README.rst000066400000000000000000000004521371415033200162400ustar00rootroot00000000000000colcon-metadata =============== An extension for `colcon-core `_ to fetch and manage package metadata from repositories. For an example repository containing metadata see `colcon-metadata-repository `_. colcon-metadata-0.2.5/appveyor.yml000066400000000000000000000012151371415033200171370ustar00rootroot00000000000000version: '{build}' environment: matrix: - PYTHON: "C:\\Python35-x64" install: - "%PYTHON%\\python.exe -m pip install -U setuptools" # install_requires - "%PYTHON%\\python.exe -m pip install -U git+https://github.com/colcon/colcon-core" - "%PYTHON%\\python.exe -m pip install -U PyYAML" # tests_require - "%PYTHON%\\python.exe -m pip install -U flake8-blind-except flake8-builtins flake8-class-newline flake8-comprehensions flake8-deprecated flake8-docstrings flake8-quotes pep8-naming pylint pytest pytest-cov scspell3k" build: off test_script: # invoke pytest - "%PYTHON%\\python.exe -m pytest --cov=colcon_metadata --cov-branch" colcon-metadata-0.2.5/colcon_metadata/000077500000000000000000000000001371415033200176655ustar00rootroot00000000000000colcon-metadata-0.2.5/colcon_metadata/__init__.py000066400000000000000000000001521371415033200217740ustar00rootroot00000000000000# Copyright 2016-2020 Dirk Thomas # Licensed under the Apache License, Version 2.0 __version__ = '0.2.5' colcon-metadata-0.2.5/colcon_metadata/metadata/000077500000000000000000000000001371415033200214455ustar00rootroot00000000000000colcon-metadata-0.2.5/colcon_metadata/metadata/__init__.py000066400000000000000000000066411371415033200235650ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from collections import defaultdict import os from colcon_core.location import get_config_path from colcon_core.logging import colcon_logger logger = colcon_logger.getChild(__name__) metadata_by_name = defaultdict(dict) metadata_by_path = defaultdict(dict) def get_metadata_path(): """ Get the path where metadata is stored. :rtype: Path """ return get_config_path() / 'metadata' def get_metadata_files(path=None): """ Get the paths of all metadata files. The metadata path is recursively being crawled for files ending in `.meta`. Directories starting with a dot (`.`) are being ignored. :rtype: list """ metadata_path = path or get_metadata_path() if not metadata_path.is_dir(): return [] files = [] for dirpath, dirnames, filenames in os.walk( str(metadata_path), followlinks=True ): # skip subdirectories starting with a dot dirnames[:] = filter(lambda d: not d.startswith('.'), dirnames) dirnames.sort() for filename in sorted(filenames): if not filename.endswith('.meta'): continue path = os.path.join(dirpath, filename) files.append(path) return files def merge_metadata(dst_dict, src_dict, meta_source): """ Merge the data from one dictionary into another. For each key of the other dictionary ``merge_metadata_value()`` is being called to set or update the key in the destination dictionary. :param dst_dict: The dictionary to be updated :param src_dict: The dictionary containing the information to be merged into the destination dictionary :param str meta_source: The source of the metadata, only used for log messages """ for key, value in src_dict.items(): merge_metadata_value(dst_dict, key, value, meta_source) def merge_metadata_value(dict_, key, value, meta_source): """ Set or update a key of a dictionary. If the key exists and the passed value as well as the current value of the key are dictionaries then the current values are being updated with the passed values. If the key exists and the passed value as well as the current value of the key are lists then the passed values are being appended to the current values. Otherwise the key is being set to the passed value potentially overwriting an existing value. :param dict_: The dictionary to be updated :param key: The key to set or update :param value: The value used to set or update the key :param str meta_source: The source of the metadata, only used for log messages """ old_value = dict_.get(key, None) if isinstance(old_value, dict) and isinstance(value, dict): # update dictionary old_value.update(value) return if isinstance(old_value, list) and isinstance(value, list): # extend list old_value += value return if isinstance(old_value, set) and isinstance(value, set): # union update set old_value |= value return if old_value is not None and type(old_value) != type(value): logger.warning( "metadata from '{meta_source}' overwrites '{key}' with different " "type from value '{old_value}' to '{value}'".format_map(locals())) # overwrite existing value dict_[key] = value colcon-metadata-0.2.5/colcon_metadata/metadata/colcon_meta.py000066400000000000000000000073121371415033200243050ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import os from colcon_core.package_augmentation import PackageAugmentationExtensionPoint from colcon_core.package_augmentation import update_descriptor from colcon_core.package_identification import logger from colcon_core.package_identification \ import PackageIdentificationExtensionPoint from colcon_core.plugin_system import satisfies_version from colcon_metadata.metadata import metadata_by_name from colcon_metadata.metadata import metadata_by_path class ColconMetadataPackageIdentification( PackageIdentificationExtensionPoint, PackageAugmentationExtensionPoint, ): """Provide meta information from `.colcon` files.""" # the priority needs to be higher than other extensions in order to # populate the descriptor with meta data before those are invoked PRIORITY = 180 def __init__(self): # noqa: D107 super().__init__() satisfies_version( PackageIdentificationExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') satisfies_version( PackageAugmentationExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def identify(self, desc): # noqa: D102 if os.path.realpath(str(desc.path)) in metadata_by_path: metadata2 = metadata_by_path[os.path.realpath(str(desc.path))] if metadata2.get('type'): if desc.type is None: desc.type = metadata2.get('type') logger.info( "Package '{desc.path}' has configured type " "'{desc.type}'".format_map(locals())) elif desc.type != metadata2.get('type'): logger.warning( "type '%s' of package '%s' does not match configured " "type '%s'", desc.type, desc.path, metadata2.get('type')) if metadata2.get('name'): if desc.name is None: desc.name = metadata2.get('name') logger.info( "Package '{desc.path}' has configured name " "'{desc.name}'" .format_map(locals())) elif desc.name != metadata2.get('name'): logger.warning( "name '%s' of package '%s' does not match configured " "name '%s'", desc.name, desc.path, metadata2.get('name')) if desc.name in metadata_by_name: data = metadata_by_name[desc.name] if 'type' in data: # if the package name was defined based on the path # then ignore the type defined for the package name if desc.type is not None and desc.type != data['type']: logger.warning( "type '{desc.type}' of package '{desc.name}' " "does not match configured type '{data[type]}'" .format_map(locals())) else: desc.type = data['type'] def augment_package( self, desc, *, additional_argument_names ): # noqa: D102 # deliberatively ignore the package type # since this extension can contribute meta information to any package if desc.name in metadata_by_name: update_descriptor( desc, metadata_by_name[desc.name], additional_argument_names=additional_argument_names) if os.path.realpath(str(desc.path)) in metadata_by_path: update_descriptor( desc, metadata_by_path[os.path.realpath(str(desc.path))], additional_argument_names=additional_argument_names) colcon-metadata-0.2.5/colcon_metadata/metadata/colcon_pkg.py000066400000000000000000000056711371415033200241460ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from colcon_core.logging import colcon_logger from colcon_core.package_augmentation import PackageAugmentationExtensionPoint from colcon_core.package_augmentation import update_descriptor from colcon_core.package_identification \ import PackageIdentificationExtensionPoint from colcon_core.plugin_system import satisfies_version import yaml logger = colcon_logger.getChild(__name__) class ColconPkgPackageIdentification( PackageIdentificationExtensionPoint, PackageAugmentationExtensionPoint, ): """Provide meta information from `colcon.pkg` files.""" # the priority needs to be higher than other extensions in order to # populate the descriptor with meta data before those are invoked PRIORITY = 200 def __init__(self): # noqa: D107 super().__init__() satisfies_version( PackageIdentificationExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') satisfies_version( PackageAugmentationExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def identify(self, desc): # noqa: D102 data = self._get_colcon_pkg_data(desc.path) if not data: return # check for package type if 'type' in data: if desc.type is not None and desc.type != data['type']: logger.warning( "Type '%s' of package '%s' does not match configured " "type '%s'", desc.type, desc.path, data['type']) else: logger.info( "Setting type '%s' of package '%s' from colcon.pkg", data['type'], desc.path) desc.type = data['type'] # check for package name if 'name' in data: if desc.name is not None and desc.name != data['name']: logger.warning( "Name '%s' of package '%s' does not match configured " "name '%s'", desc.name, desc.path, data['name']) else: logger.info( "Setting name '%s' of package '%s' from colcon.pkg", data['name'], desc.path) desc.name = data['name'] def augment_package( self, desc, *, additional_argument_names ): # noqa: D102 data = self._get_colcon_pkg_data(desc.path) if not data: return logger.info( "Updating descriptor of package '%s' from colcon.pkg: %s", desc.path, data) update_descriptor( desc, data, additional_argument_names=additional_argument_names) def _get_colcon_pkg_data(self, basepath): # check for a colcon.pkg file in the root of the package directory colcon_pkg_path = basepath / 'colcon.pkg' if not colcon_pkg_path.is_file(): return None content = colcon_pkg_path.read_text() return yaml.safe_load(content) colcon-metadata-0.2.5/colcon_metadata/metadata/repository.py000066400000000000000000000062711371415033200242440ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import os import socket import time from urllib.error import HTTPError from urllib.error import URLError from urllib.request import urlopen from colcon_core.location import get_config_path from colcon_core.logging import colcon_logger from colcon_metadata.metadata import get_metadata_files from colcon_metadata.metadata import get_metadata_path import yaml logger = colcon_logger.getChild(__name__) """The path of the yaml file describing the metadata repositories.""" metadata_repositories_file = get_config_path() / 'metadata_repositories.yaml' def get_repositories(): """ Get the registered repositories. :rtype: dict """ global metadata_repositories_file if not metadata_repositories_file.exists(): return {} if metadata_repositories_file.is_dir(): raise IsADirectoryError() content = metadata_repositories_file.read_text() data = yaml.safe_load(content) assert isinstance(data, dict), 'The content of the configuration file ' \ "'%s' should be a dictionary" % metadata_repositories_file return data def set_repositories(repositories): """ Persist the passed repositories in the configuration file. :param dict repositories: The repositories """ assert isinstance(repositories, dict), \ 'The passed repositories should be a dictionary' global metadata_repositories_file data = yaml.dump(repositories, default_flow_style=False) os.makedirs(str(metadata_repositories_file.parent), exist_ok=True) with metadata_repositories_file.open('w') as h: h.write(data) def get_repository_metadata_files(*, repository_name): """ Get the configuration files for a specific repository. :param str repository_name: The repository name :rtype: list """ return get_metadata_files(get_metadata_path() / repository_name) def load_url(url, retry=2, retry_period=1, timeout=10): """ Load a URL. :param int retry: The number of retries in case the request fails :param int retry_period: The period to wait before the first retry. Every subsequent retry will double the period. :param int timeout: The timeout for each request :rtype: str """ try: h = urlopen(url, timeout=timeout) except HTTPError as e: if e.code == 503 and retry: time.sleep(retry_period) return load_url( url, retry=retry - 1, retry_period=retry_period * 2, timeout=timeout) e.msg += ' (%s)' % url raise except URLError as e: if isinstance(e.reason, socket.timeout) and retry: time.sleep(retry_period) return load_url( url, retry=retry - 1, retry_period=retry_period * 2, timeout=timeout) raise URLError(str(e) + ' (%s)' % url) except socket.timeout as e: if retry: time.sleep(retry_period) return load_url( url, retry=retry - 1, retry_period=retry_period * 2, timeout=timeout) raise socket.timeout(str(e) + ' (%s)' % url) content = h.read() return content.decode('utf-8') colcon-metadata-0.2.5/colcon_metadata/package_discovery/000077500000000000000000000000001371415033200233475ustar00rootroot00000000000000colcon-metadata-0.2.5/colcon_metadata/package_discovery/__init__.py000066400000000000000000000000001371415033200254460ustar00rootroot00000000000000colcon-metadata-0.2.5/colcon_metadata/package_discovery/colcon_meta.py000066400000000000000000000070011371415033200262020ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import os from pathlib import Path from colcon_core.logging import colcon_logger from colcon_core.package_discovery import PackageDiscoveryExtensionPoint from colcon_core.plugin_system import satisfies_version from colcon_metadata.metadata import get_metadata_files from colcon_metadata.metadata import get_metadata_path from colcon_metadata.metadata import merge_metadata from colcon_metadata.metadata import metadata_by_name from colcon_metadata.metadata import metadata_by_path import yaml logger = colcon_logger.getChild(__name__) class ColconMetadataDiscovery(PackageDiscoveryExtensionPoint): """Provide meta information from `.meta` files.""" # the priority needs to be higher than other extensions # in order for metadata to be added before those are invoked PRIORITY = 200 def __init__(self): # noqa: D107 super().__init__() satisfies_version( PackageDiscoveryExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def add_arguments(self, *, parser, with_default): # noqa: D102 parser.add_argument( '--ignore-user-meta', action='store_true', help='Ignore `*.meta` files in the user config directory `%s`' % get_metadata_path()) parser.add_argument( '--metas', nargs='*', metavar='PATH', default=['./colcon.meta'], help='The directories containing a `colcon.meta` file or paths to ' 'arbitrary files containing the same meta information ' '(default: ./colcon.meta)') def has_parameters(self, *, args): # noqa: D102 if not args.ignore_user_meta: for path in get_metadata_files(): self._add(Path(path)) for meta in args.metas or []: path = Path(meta) if not path.exists(): continue if path.is_dir(): path_file = path / 'colcon.meta' if not path_file.exists(): continue path = path_file self._add(path) # doesn't implement the `discover()` method # since `has_parameters()` always returns False return False def _add(self, meta_path): content = meta_path.read_text() try: data = yaml.safe_load(content) except Exception as e: logger.warning( "Skipping metadata file '%s' since it failed to parse: %s" % (meta_path.absolute(), e)) return if data is None: logger.info( "Empty metadata file '%s'" % meta_path.absolute()) return if not isinstance(data, dict): logger.warning( "Skipping metadata file '%s' since it doesn't contain a dict" % meta_path.absolute()) return logger.info( "Using configuration from '%s'" % meta_path.absolute()) if 'names' in data and isinstance(data['names'], dict): for name, v in data['names'].items(): merge_metadata(metadata_by_name[name], v, meta_path.absolute()) if 'paths' in data and isinstance(data['paths'], dict): for path, value in data['paths'].items(): path = meta_path.parent / path merge_metadata( metadata_by_path[os.path.realpath(str(path))], value, meta_path.absolute()) colcon-metadata-0.2.5/colcon_metadata/subverb/000077500000000000000000000000001371415033200213355ustar00rootroot00000000000000colcon-metadata-0.2.5/colcon_metadata/subverb/__init__.py000066400000000000000000000032111371415033200234430ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from colcon_core.logging import colcon_logger from colcon_core.plugin_system import instantiate_extensions from colcon_core.plugin_system import order_extensions_by_name logger = colcon_logger.getChild(__name__) class MetadataSubverbExtensionPoint: """ The interface for metadata subverb extensions. A metadata subverb extension provides a subverb to the `metadata` verb of the command line tool. For each instance the attribute `SUBVERB_NAME` is being set to the basename of the entry point registering the extension. """ """The version of the metadata subverb extension interface.""" EXTENSION_POINT_VERSION = '1.0' def add_arguments(self, *, parser): """ Add command line arguments specific to the metadata subverb. The method is intended to be overridden in a subclass. :param parser: The argument parser """ pass def main(self, *, context): """ Execute the metadata subverb extension logic. This method must be overridden in a subclass. :param context: The context providing the parsed command line arguments :returns: The return code """ raise NotImplementedError() def get_subverb_extensions(): """ Get the available subverb extensions. The extensions are ordered by their entry point name. :rtype: OrderedDict """ extensions = instantiate_extensions(__name__) for name, extension in extensions.items(): extension.SUBVERB_NAME = name return order_extensions_by_name(extensions) colcon-metadata-0.2.5/colcon_metadata/subverb/add.py000066400000000000000000000033631371415033200224440ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from argparse import ArgumentTypeError from colcon_core.plugin_system import satisfies_version from colcon_metadata.metadata.repository import get_repositories from colcon_metadata.metadata.repository import set_repositories from colcon_metadata.subverb import MetadataSubverbExtensionPoint class AddMetadataSubverb(MetadataSubverbExtensionPoint): """Add the URL of a repository index.""" def __init__(self): # noqa: D107 super().__init__() satisfies_version( MetadataSubverbExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def add_arguments(self, *, parser): # noqa: D102 parser.add_argument( 'name', type=_non_empty_string_without_pathsep, help='The unique name identifying the repository') parser.add_argument( 'url', type=_url_string, help='The url of a metadata repository index') def main(self, *, context): # noqa: D102 repos = get_repositories() if context.args.name in repos.keys(): return "A repository with the name '{context.args.name}' " \ 'already exists'.format_map(locals()) repos[context.args.name] = context.args.url set_repositories(repos) def _non_empty_string_without_pathsep(value): if not value: raise ArgumentTypeError('must be a non-empty string') for pathsep in ('/', '\\'): if pathsep in value: raise ArgumentTypeError( "must not contain '{pathsep}'".format_map(locals())) return value def _url_string(value): if '://' not in value: raise ArgumentTypeError("must contain '://'") return value colcon-metadata-0.2.5/colcon_metadata/subverb/list.py000066400000000000000000000033721371415033200226670ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from colcon_core.plugin_system import satisfies_version from colcon_metadata.metadata.repository import get_repositories from colcon_metadata.metadata.repository import get_repository_metadata_files from colcon_metadata.subverb import MetadataSubverbExtensionPoint class ListMetadataSubverb(MetadataSubverbExtensionPoint): """List all repositories and their metadata.""" def __init__(self): # noqa: D107 super().__init__() satisfies_version( MetadataSubverbExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def add_arguments(self, *, parser): # noqa: D102 argument = parser.add_argument( 'name', nargs='?', help='Only list the information for a specific repository') try: from argcomplete.completers import ChoicesCompleter except ImportError: pass else: repos = get_repositories() argument.completer = \ ChoicesCompleter(repos.keys()) def main(self, *, context): # noqa: D102 repos = get_repositories() if context.args.name and context.args.name not in repos.keys(): return "Passed repository name '{context.args.name}' is unknown" \ .format_map(locals()) for name in sorted(repos.keys()): if context.args.name and context.args.name != name: continue url = repos[name] print('{name}: {url}'.format_map(locals())) metadata_files = get_repository_metadata_files( repository_name=name) for path in sorted(metadata_files): print('- {path}'.format_map(locals())) colcon-metadata-0.2.5/colcon_metadata/subverb/remove.py000066400000000000000000000025501371415033200232060ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from colcon_core.plugin_system import satisfies_version from colcon_metadata.metadata.repository import get_repositories from colcon_metadata.metadata.repository import set_repositories from colcon_metadata.subverb import MetadataSubverbExtensionPoint class RemoveMetadataSubverb(MetadataSubverbExtensionPoint): """Remove a repository from the list of indexes.""" def __init__(self): # noqa: D107 super().__init__() satisfies_version( MetadataSubverbExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def add_arguments(self, *, parser): # noqa: D102 argument = parser.add_argument( 'name', help='The unique name identifying the repository') try: from argcomplete.completers import ChoicesCompleter except ImportError: pass else: repos = get_repositories() argument.completer = \ ChoicesCompleter(repos.keys()) def main(self, *, context): # noqa: D102 repos = get_repositories() if context.args.name not in repos.keys(): return "A repository with the name '{context.args.name}' " \ "doesn't exist".format_map(locals()) del repos[context.args.name] set_repositories(repos) colcon-metadata-0.2.5/colcon_metadata/subverb/update.py000066400000000000000000000137441371415033200232020ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import os import sys from colcon_core.plugin_system import satisfies_version from colcon_metadata.metadata import get_metadata_files from colcon_metadata.metadata import get_metadata_path from colcon_metadata.metadata.repository import get_repositories from colcon_metadata.metadata.repository import get_repository_metadata_files from colcon_metadata.metadata.repository import load_url from colcon_metadata.subverb import MetadataSubverbExtensionPoint import yaml class UpdateMetadataSubverb(MetadataSubverbExtensionPoint): """Update the metadata from the repository indexes.""" def __init__(self): # noqa: D107 super().__init__() satisfies_version( MetadataSubverbExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def add_arguments(self, *, parser): # noqa: D102 parser.description += '\n\n' \ 'For each repository all metadata files are being fetched. ' \ 'The status if each metadata file is indicated by the following ' \ 'symbols:\n' \ ' + added new metadata file\n' \ ' * updated the existing metadata file\n' \ ' . existing metadata file was already the same\n' \ ' - renamed obsolete metadata file' argument = parser.add_argument( 'name', nargs='?', help='Only update the metadata from a specific repository') try: from argcomplete.completers import ChoicesCompleter except ImportError: pass else: repos = get_repositories() argument.completer = \ ChoicesCompleter(repos.keys()) def main(self, *, context): # noqa: D102 repos = get_repositories() if context.args.name and context.args.name not in repos.keys(): return "Passed repository name '{context.args.name}' is unknown" \ .format_map(locals()) # IDEA fetch all resources in parallel rc = 0 for name in sorted(repos.keys()): if context.args.name and context.args.name != name: continue # fetch the repository index index_url = repos[name] print('fetching {name}: {index_url} ...'.format_map(locals())) try: content = load_url(index_url) except Exception as e: print(' ', str(e), file=sys.stderr) rc = 1 continue # parse the repository index try: data = yaml.safe_load(content) except Exception as e: print(' ', str(e), file=sys.stderr) rc = 1 continue if not isinstance(data, dict) or 'metadata' not in data.keys(): print(' The repository index should be a dictionary with a ' "'metadata' key, but it is: {data}".format_map(locals())) rc = 1 continue # get existing metadata files to remove obsolete ones later metadata_files_before = get_repository_metadata_files( repository_name=name) # fetch all metadata files referenced in the index metadata_urls = data['metadata'] metadata_basenames = set() for metadata_url in metadata_urls: # if metadata URL is relative prefix the dirname of the index if ( '://' not in metadata_url and not os.path.isabs(metadata_url) ): metadata_url = \ os.path.dirname(index_url) + '/' + metadata_url # fetch the metadata file print(' fetching {metadata_url} ...'.format_map(locals())) try: content = load_url(metadata_url) except Exception as e: print(' -', str(e), file=sys.stderr) rc = 1 continue # save the metadata file metadata_basename = os.path.basename(metadata_url) if metadata_basename in metadata_basenames: print(' Multiple metadata files with the same basename ' "'{metadata_basename}'".format_map(locals()), file=sys.stderr) else: metadata_basenames.add(metadata_basename) destination_basepath = get_metadata_path() / name os.makedirs(str(destination_basepath), exist_ok=True) destination_path = destination_basepath / metadata_basename if not destination_path.exists(): mod = '+' else: if content == destination_path.read_text(): mod = '.' else: # IDEA show the diff if the file already exists mod = '*' print(' ', mod, str(destination_path)) with destination_path.open('w') as h: h.write(content) # remove / rename obsolete metadata files for metadata_file in metadata_files_before: if os.path.basename(metadata_file) not in metadata_basenames: os.rename(metadata_file, metadata_file + '.obsolete') print(' - {metadata_file} -> *.obsolete' .format_map(locals())) # remove / rename metadata files from obsolete repositories obsolete_files = set(get_metadata_files()) for name in repos.keys(): obsolete_files -= set(get_repository_metadata_files( repository_name=name)) for metadata_file in sorted(obsolete_files): os.rename(metadata_file, metadata_file + '.obsolete') print(' - {metadata_file} -> *.obsolete'.format_map(locals())) return rc colcon-metadata-0.2.5/colcon_metadata/verb/000077500000000000000000000000001371415033200206235ustar00rootroot00000000000000colcon-metadata-0.2.5/colcon_metadata/verb/__init__.py000066400000000000000000000000001371415033200227220ustar00rootroot00000000000000colcon-metadata-0.2.5/colcon_metadata/verb/metadata.py000066400000000000000000000022411371415033200227540ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from colcon_core.command import add_subparsers from colcon_core.plugin_system import satisfies_version from colcon_core.verb import VerbExtensionPoint from colcon_metadata.subverb import get_subverb_extensions class MetadataVerb(VerbExtensionPoint): """Manage metadata of packages.""" def __init__(self): # noqa: D107 super().__init__() satisfies_version(VerbExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') self._subparser = None def add_arguments(self, *, parser): # noqa: D102 # remember the subparser to print usage in case no subverb is passed self._subparser = parser # get subverb extensions and let them add their arguments subverb_extensions = get_subverb_extensions() add_subparsers( parser, 'colcon metadata', subverb_extensions, attribute='subverb_name') def main(self, *, context): # noqa: D102 # error: no subverb provided if context.args.subverb_name is None: print(self._subparser.format_usage()) return 'Error: No subverb provided' colcon-metadata-0.2.5/setup.cfg000066400000000000000000000045751371415033200164040ustar00rootroot00000000000000[metadata] name = colcon-metadata version = attr: colcon_metadata.__version__ url = https://colcon.readthedocs.io project_urls = Changelog = https://github.com/colcon/colcon-metadata/milestones?direction=desc&sort=due_date&state=closed GitHub = https://github.com/colcon/colcon-metadata/ author = Dirk Thomas author_email = web@dirk-thomas.net maintainer = Dirk Thomas maintainer_email = web@dirk-thomas.net classifiers = Development Status :: 3 - Alpha Environment :: Plugins Intended Audience :: Developers License :: OSI Approved :: Apache Software License Operating System :: MacOS Operating System :: Microsoft :: Windows Operating System :: POSIX Programming Language :: Python Topic :: Software Development :: Build Tools license = Apache License, Version 2.0 description = Extension for colcon to read package metadata from files. long_description = file: README.rst keywords = colcon [options] install_requires = colcon-core PyYAML packages = find: tests_require = flake8>=3.6.0 flake8-blind-except flake8-builtins flake8-class-newline flake8-comprehensions flake8-deprecated flake8-docstrings flake8-import-order flake8-quotes pep8-naming pylint pytest pytest-cov scspell3k>=2.2 zip_safe = true [tool:pytest] filterwarnings = error junit_suite_name = colcon-metadata [options.entry_points] colcon_core.extension_point = colcon_metadata.subverb = colcon_metadata.subverb:MetadataSubverbExtensionPoint colcon_core.package_augmentation = colcon_meta = colcon_metadata.metadata.colcon_meta:ColconMetadataPackageIdentification colcon_pkg = colcon_metadata.metadata.colcon_pkg:ColconPkgPackageIdentification colcon_core.package_discovery = colcon_meta = colcon_metadata.package_discovery.colcon_meta:ColconMetadataDiscovery colcon_core.package_identification = colcon_meta = colcon_metadata.metadata.colcon_meta:ColconMetadataPackageIdentification colcon_pkg = colcon_metadata.metadata.colcon_pkg:ColconPkgPackageIdentification colcon_core.verb = metadata = colcon_metadata.verb.metadata:MetadataVerb colcon_metadata.subverb = add = colcon_metadata.subverb.add:AddMetadataSubverb list = colcon_metadata.subverb.list:ListMetadataSubverb remove = colcon_metadata.subverb.remove:RemoveMetadataSubverb update = colcon_metadata.subverb.update:UpdateMetadataSubverb [flake8] import-order-style = google colcon-metadata-0.2.5/setup.py000066400000000000000000000001721371415033200162620ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from setuptools import setup setup() colcon-metadata-0.2.5/stdeb.cfg000066400000000000000000000002161371415033200163310ustar00rootroot00000000000000[colcon-metadata] No-Python2: Depends3: python3-colcon-core, python3-yaml Suite: xenial bionic focal stretch buster X-Python3-Version: >= 3.5 colcon-metadata-0.2.5/test/000077500000000000000000000000001371415033200155275ustar00rootroot00000000000000colcon-metadata-0.2.5/test/spell_check.words000066400000000000000000000003331371415033200210620ustar00rootroot00000000000000apache argcomplete argparse basenames basepath colcon completers defaultdict deliberatively iterdir nargs noqa pathlib plugin pytest rtype scspell setuptools subparser subparsers subverb thomas urllib urlopen urls yaml colcon-metadata-0.2.5/test/test_copyright_license.py000066400000000000000000000024271371415033200226570ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from pathlib import Path import sys def test_copyright_license(): missing = check_files([Path(__file__).parents[1]]) assert not len(missing), \ 'In some files no copyright / license line was found' def check_files(paths): missing = [] for path in paths: if path.is_dir(): for p in sorted(path.iterdir()): if p.name.startswith('.'): continue if p.name.endswith('.py') or p.is_dir(): missing += check_files([p]) if path.is_file(): content = path.read_text() if not content: continue lines = content.splitlines() has_copyright = \ any(line for line in lines if line.startswith('# Copyright')) has_license = \ '# Licensed under the Apache License, Version 2.0' in lines if not has_copyright or not has_license: print( 'Could not find copyright / license in:', path, file=sys.stderr) missing .append(path) else: print('Found copyright / license in:', path) return missing colcon-metadata-0.2.5/test/test_flake8.py000066400000000000000000000030021371415033200203050ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import logging from pathlib import Path import sys from flake8 import LOG from flake8.api.legacy import get_style_guide # avoid debug and info messages from flake8 internals LOG.setLevel(logging.WARN) def test_flake8(): style_guide = get_style_guide( extend_ignore=['D100', 'D104'], show_source=True, ) style_guide_tests = get_style_guide( extend_ignore=['D100', 'D101', 'D102', 'D103', 'D104', 'D105', 'D107'], show_source=True, ) stdout = sys.stdout sys.stdout = sys.stderr # implicitly calls report_errors() report = style_guide.check_files([ str(Path(__file__).parents[1] / 'colcon_metadata'), ]) report_tests = style_guide_tests.check_files([ str(Path(__file__).parents[1] / 'test'), ]) sys.stdout = stdout total_errors = report.total_errors + report_tests.total_errors if total_errors: # pragma: no cover # output summary with per-category counts print() if report.total_errors: report._application.formatter.show_statistics(report._stats) if report_tests.total_errors: report_tests._application.formatter.show_statistics( report_tests._stats) print( 'flake8 reported {total_errors} errors' .format_map(locals()), file=sys.stderr) assert not total_errors, \ 'flake8 reported {total_errors} errors'.format_map(locals()) colcon-metadata-0.2.5/test/test_spell_check.py000066400000000000000000000035551371415033200214240ustar00rootroot00000000000000# Copyright 2016-2019 Dirk Thomas # Licensed under the Apache License, Version 2.0 from pathlib import Path import pytest from scspell import Report from scspell import SCSPELL_BUILTIN_DICT from scspell import spell_check spell_check_words_path = Path(__file__).parent / 'spell_check.words' @pytest.fixture(scope='module') def known_words(): global spell_check_words_path return spell_check_words_path.read_text().splitlines() def test_spell_check(known_words): source_filenames = [Path(__file__).parents[1] / 'setup.py'] + \ list( (Path(__file__).parents[1] / 'colcon_metadata') .glob('**/*.py')) + \ list((Path(__file__).parents[1] / 'test').glob('**/*.py')) for source_filename in sorted(source_filenames): print('Spell checking:', source_filename) # check all files report = Report(known_words) spell_check( [str(p) for p in source_filenames], base_dicts=[SCSPELL_BUILTIN_DICT], report_only=report, additional_extensions=[('', 'Python')]) unknown_word_count = len(report.unknown_words) assert unknown_word_count == 0, \ 'Found {unknown_word_count} unknown words: '.format_map(locals()) + \ ', '.join(sorted(report.unknown_words)) unused_known_words = set(known_words) - report.found_known_words unused_known_word_count = len(unused_known_words) assert unused_known_word_count == 0, \ '{unused_known_word_count} words in the word list are not used: ' \ .format_map(locals()) + ', '.join(sorted(unused_known_words)) def test_spell_check_word_list_order(known_words): assert known_words == sorted(known_words), \ 'The word list should be ordered alphabetically' def test_spell_check_word_list_duplicates(known_words): assert len(known_words) == len(set(known_words)), \ 'The word list should not contain duplicates'