pax_global_header00006660000000000000000000000064145743744400014526gustar00rootroot0000000000000052 comment=9d68f1ab4b351126721daf397a15fa442527d275 colcon-package-information-0.4.0/000077500000000000000000000000001457437444000167205ustar00rootroot00000000000000colcon-package-information-0.4.0/.github/000077500000000000000000000000001457437444000202605ustar00rootroot00000000000000colcon-package-information-0.4.0/.github/workflows/000077500000000000000000000000001457437444000223155ustar00rootroot00000000000000colcon-package-information-0.4.0/.github/workflows/ci.yaml000066400000000000000000000002221457437444000235700ustar00rootroot00000000000000--- name: Run tests on: push: branches: ['master'] pull_request: jobs: pytest: uses: colcon/ci/.github/workflows/pytest.yaml@main colcon-package-information-0.4.0/LICENSE000066400000000000000000000261361457437444000177350ustar00rootroot00000000000000 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-package-information-0.4.0/README.rst000066400000000000000000000002521457437444000204060ustar00rootroot00000000000000colcon-package-information ========================== An extension for `colcon-core `_ to provide information about the packages. colcon-package-information-0.4.0/colcon_package_information/000077500000000000000000000000001457437444000242555ustar00rootroot00000000000000colcon-package-information-0.4.0/colcon_package_information/__init__.py000066400000000000000000000001521457437444000263640ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 __version__ = '0.4.0' colcon-package-information-0.4.0/colcon_package_information/package_augmentation/000077500000000000000000000000001457437444000304235ustar00rootroot00000000000000colcon-package-information-0.4.0/colcon_package_information/package_augmentation/__init__.py000066400000000000000000000000001457437444000325220ustar00rootroot00000000000000check_dependency_constraint.py000066400000000000000000000067221457437444000364440ustar00rootroot00000000000000colcon-package-information-0.4.0/colcon_package_information/package_augmentation# Copyright 2019 Dirk Thomas # Licensed under the Apache License, Version 2.0 import operator from colcon_core.package_augmentation import logger as \ package_augmentation_logger from colcon_core.package_augmentation import PackageAugmentationExtensionPoint from colcon_core.plugin_system import satisfies_version from packaging.version import Version logger = package_augmentation_logger.getChild('check_dependency_constraint') class CheckDependencyConstraintPackageAugmentation( PackageAugmentationExtensionPoint ): """Check package dependency constraints.""" # the priority needs to be lower than other extensions to allow them to # augment dependency information before PRIORITY = 1 def __init__(self): # noqa: D107 super().__init__() satisfies_version( PackageAugmentationExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def augment_packages( # noqa: D102 self, descs, *, additional_argument_names=None ): descs_dict = {desc.name: desc for desc in descs} for name, desc in descs_dict.items(): deps = desc.get_dependencies() for dep in deps: # skip dependencies which don't have a descriptor if dep.name not in descs_dict: continue self._check_version_constraints( desc, dep, descs_dict[dep.name]) def _check_version_constraints(self, desc, dep, dep_desc): # if the dependency descriptor doesn't have a version there is nothing # to compare to if 'version' not in dep_desc.metadata: return try: dep_version = Version(dep_desc.metadata['version']) except Exception: # noqa: B902 # skip check if the version fails to parse return def lte(a, b): return operator.lt(a, b) or operator.eq(a, b) def gte(a, b): return operator.gt(a, b) or operator.eq(a, b) operators = { 'version_lt': (operator.lt, 'less than'), 'version_lte': (lte, 'less than or equal to'), 'version_eq': (operator.eq, 'equal to'), 'version_neq': (operator.ne, 'not equal to'), 'version_gte': (gte, 'greater than or equal to'), 'version_gt': (operator.gt, 'greater than'), } for key, value in dep.metadata.items(): # only consider version operator metadata if key not in operators: continue op, msg = operators[key] try: version_constraint = Version(value) except Exception: # noqa: B902 logger.error( "Failed to parse version '" + value + "' with " + "constraint '" + msg + "' for dependency " + dep.name + ' in package ' + desc.name) # skip check if the version fails to parse continue if not op(dep_version, version_constraint): logger.warning( desc.name + ' depends on ' + dep.name + ' which has version ' + dep_desc.metadata['version'] + ' but expects it to be ' + msg + ' ' + value) else: logger.debug( desc.name + ' depends on ' + dep.name + ' which has version ' + dep_desc.metadata['version'] + ' which satisfies to be ' + msg + ' ' + value) colcon-package-information-0.4.0/colcon_package_information/verb/000077500000000000000000000000001457437444000252135ustar00rootroot00000000000000colcon-package-information-0.4.0/colcon_package_information/verb/__init__.py000066400000000000000000000000001457437444000273120ustar00rootroot00000000000000colcon-package-information-0.4.0/colcon_package_information/verb/graph.py000066400000000000000000000323121457437444000266670ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from collections import defaultdict from collections import OrderedDict import itertools import os from pathlib import Path from colcon_core.package_selection import add_arguments \ as add_packages_arguments from colcon_core.package_selection import get_package_descriptors from colcon_core.package_selection import select_package_decorators from colcon_core.plugin_system import satisfies_version from colcon_core.topological_order import topological_order_packages from colcon_core.verb import VerbExtensionPoint class GraphVerb(VerbExtensionPoint): """Generate a visual representation of the dependency graph.""" def __init__(self): # noqa: D107 super().__init__() satisfies_version(VerbExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def add_arguments(self, *, parser): # noqa: D102 # only added so that package selection arguments can be used # which use the build directory to store state information parser.add_argument( '--build-base', default='build', help='The base path for all build directories (default: build)') add_packages_arguments(parser) group = parser.add_mutually_exclusive_group() group.add_argument( '--dot', action='store_true', default=False, help='Output topological graph in DOT ' '(e.g. pass the output to dot: ` | dot -Tpng -o graph.png`), ' 'legend: blue=build, red=run, tan=test, dashed=indirect') group.add_argument( '--density', action='store_true', default=False, help='Output density of the graph (only without --dot)') parser.add_argument( '--legend', action='store_true', default=False, help='Output legend for the graph') parser.add_argument( '--dot-cluster', action='store_true', default=False, help='Cluster packages by their filesystem path (only affects ' '--dot)') parser.add_argument( '--dot-include-skipped', action='store_true', default=False, help='Also output skipped packages (only affects --dot)') def main(self, *, context): # noqa: D102 args = context.args descriptors = get_package_descriptors(args) decorators = topological_order_packages( descriptors, recursive_categories=('run', )) select_package_decorators(args, decorators) if not args.dot: if args.legend: print('+ marks when the package in this row can be processed') print('* marks a direct dependency ' 'from the package indicated by the + in the same column ' 'to the package in this row') print('. marks a transitive dependency') print() # draw dependency graph in ASCII shown_decorators = list(filter(lambda d: d.selected, decorators)) max_length = max([ len(m.descriptor.name) for m in shown_decorators] + [0]) lines = [ m.descriptor.name.ljust(max_length + 2) for m in shown_decorators] depends = [ m.descriptor.get_dependencies() for m in shown_decorators] rec_depends = [ m.descriptor.get_recursive_dependencies( [d.descriptor for d in decorators], recursive_categories=('run', )) for m in shown_decorators] empty_cells = 0 for i, decorator in enumerate(shown_decorators): for j in range(len(lines)): if j == i: # package i is being processed lines[j] += '+' elif shown_decorators[j].descriptor.name in depends[i]: # package i directly depends on package j lines[j] += '*' elif shown_decorators[j].descriptor.name in rec_depends[i]: # package i recursively depends on package j lines[j] += '.' else: # package i doesn't depend on package j lines[j] += ' ' empty_cells += 1 if args.density: empty_fraction = \ empty_cells / (len(lines) * (len(lines) - 1)) \ if len(lines) > 1 else 1.0 # normalize to 200% since half of the matrix should be empty density_percentage = 200.0 * (1.0 - empty_fraction) print('dependency density %.2f %%' % density_percentage) print() else: # --dot lines = ['digraph graphname {'] decorators_by_name = defaultdict(set) for deco in decorators: decorators_by_name[deco.descriptor.name].add(deco) selected_pkg_names = [ m.descriptor.name for m in decorators if m.selected or args.dot_include_skipped] has_duplicate_names = \ len(selected_pkg_names) != len(set(selected_pkg_names)) selected_pkg_names = set(selected_pkg_names) # collect selected package decorators and their parent path nodes = OrderedDict() for deco in reversed(decorators): if deco.selected or args.dot_include_skipped: nodes[deco] = Path(deco.descriptor.path).parent # collect direct dependencies direct_edges = defaultdict(set) for deco in reversed(decorators): if ( not deco.selected and not args.dot_include_skipped ): continue # iterate over dependency categories for category, deps in deco.descriptor.dependencies.items(): # iterate over dependencies for dep in deps: if dep not in selected_pkg_names: continue # store the category of each dependency # use the decorator # since there might be packages with the same name direct_edges[(deco, dep)].add(category) # collect indirect dependencies indirect_edges = defaultdict(set) for deco in reversed(decorators): if not deco.selected: continue # iterate over dependency categories for category, deps in deco.descriptor.dependencies.items(): # iterate over dependencies for dep in deps: # ignore direct dependencies if dep in selected_pkg_names: continue # ignore unknown dependencies if dep not in decorators_by_name.keys(): continue # iterate over recursive dependencies for rdep in itertools.chain.from_iterable( d.recursive_dependencies for d in decorators_by_name[dep] ): if rdep not in selected_pkg_names: continue # skip edges which are redundant to direct edges if (deco, rdep) in direct_edges: continue indirect_edges[(deco, rdep)].add(category) try: # HACK Python 3.5 can't handle Path objects common_path = os.path.commonpath( [str(p) for p in nodes.values()]) except ValueError: common_path = None def get_node_data(decorator): nonlocal args nonlocal has_duplicate_names if not has_duplicate_names: # use name where possible so the dot code is easy to read return decorator.descriptor.name, \ '' if ( decorator.selected or not args.dot_include_skipped ) else '[color = "gray" fontcolor = "gray"]' # otherwise append the descriptor id to make each node unique descriptor_id = id(decorator.descriptor) return ( '{decorator.descriptor.name}_{descriptor_id}' .format_map(locals()), ' [label = "{decorator.descriptor.name}"]' .format_map(locals()), ) if not args.dot_cluster or common_path is None: # output nodes for deco in nodes.keys(): if ( not deco.selected and not args.dot_include_skipped ): continue node_name, attributes = get_node_data(deco) lines.append( ' "{node_name}"{attributes};'.format_map(locals())) else: # output clusters clusters = defaultdict(set) for deco, path in nodes.items(): clusters[path.relative_to(common_path)].add(deco) for i, cluster in zip(range(len(clusters)), clusters.items()): path, decos = cluster if path.name: # wrap cluster in subgraph lines.append( ' subgraph cluster_{i} {{'.format_map(locals())) lines.append( ' label = "{path}";'.format_map(locals())) indent = ' ' else: indent = ' ' for deco in decos: node_name, attributes = get_node_data(deco) lines.append( '{indent}"{node_name}"{attributes};' .format_map(locals())) if path.name: lines.append(' }') # output edges color_mapping = OrderedDict(( ('build', '#0000ff'), # blue ('run', '#ff0000'), # red ('test', '#d2b48c'), # tan )) for style, edges in zip( ('', ', style="dashed"'), (direct_edges, indirect_edges), ): for (deco_start, node_end), categories in edges.items(): start_name, _ = get_node_data(deco_start) for deco in decorators_by_name[node_end]: end_name, _ = get_node_data(deco) edge_alpha = '' \ if deco_start.selected and deco.selected else '77' colors = ':'.join([ color + edge_alpha for category, color in color_mapping.items() if category in categories]) lines.append( ' "{start_name}" -> "{end_name}" ' '[color="{colors}"{style}];'.format_map(locals())) if args.legend: lines.append(' subgraph cluster_legend {') lines.append(' color=gray') lines.append(' label="Legend";') lines.append(' margin=0;') # invisible nodes between the dependency edges lines.append(' node [label="", shape=none];') previous_node = '_legend_first' # an edge for each dependency type for dependency_type, color in color_mapping.items(): next_node = '_legend_' + dependency_type lines.append( ' {previous_node} -> {next_node} ' '[label="{dependency_type} dep.", color="{color}"];' .format_map(locals())) previous_node = next_node lines.append( ' {previous_node} -> _legend_last ' '[label="indirect dep.", style="dashed"];' .format_map(locals())) # layout all legend nodes on the same rank lines.append(' {') lines.append(' rank=same;') lines.append(' _legend_first;') for dependency_type in color_mapping.keys(): lines.append( ' _legend_{dependency_type};' .format_map(locals())) lines.append(' _legend_last;') lines.append(' }') lines.append(' }') lines.append('}') for line in lines: print(line) colcon-package-information-0.4.0/colcon_package_information/verb/info.py000066400000000000000000000075131457437444000265260ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import argparse import sys from colcon_core.package_selection import add_arguments \ as add_packages_arguments from colcon_core.package_selection import get_package_descriptors from colcon_core.package_selection import select_package_decorators from colcon_core.plugin_system import satisfies_version from colcon_core.topological_order import topological_order_packages from colcon_core.verb import VerbExtensionPoint class InfoVerb(VerbExtensionPoint): """Package information.""" def __init__(self): # noqa: D107 super().__init__() satisfies_version(VerbExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def add_arguments(self, *, parser): # noqa: D102 parser.add_argument( 'package_names', nargs='*', metavar='PKG_NAME', type=argument_package_name, help='Only show the information of a subset of packages') # only added so that package selection arguments can be used # which use the build directory to store state information parser.add_argument( '--build-base', default='build', help='The base path for all build directories (default: build)') add_packages_arguments(parser) def main(self, *, context): # noqa: D102 descriptors = get_package_descriptors( context.args, additional_argument_names=['*']) decorators = topological_order_packages( descriptors, recursive_categories=('run', )) select_package_decorators(context.args, decorators) if context.args.package_names: all_package_names = {d.descriptor.name for d in decorators} # warn about passed package names which are unknown for pkg_name in context.args.package_names: if pkg_name not in all_package_names: print( "Package '{pkg_name}' not found".format_map(locals()), file=sys.stderr) # filter decorators using passed package names decorators = [ d for d in decorators if d.descriptor.name in context.args.package_names] if not decorators: return 1 if not decorators: return 'No packages found' for decorator in sorted(decorators, key=lambda d: d.descriptor.name): if not decorator.selected: continue pkg = decorator.descriptor print('path:', pkg.path) print(' type:', pkg.type) print(' name:', pkg.name) if pkg.dependencies: print(' dependencies:') for category in sorted(pkg.dependencies.keys()): print( ' {category}:'.format_map(locals()), ' '.join(sorted(pkg.dependencies[category]))) if pkg.hooks: print(' hooks:', ' '.join(pkg.hooks)) if pkg.metadata: print(' metadata:') for key in sorted(pkg.metadata.keys()): value = pkg.metadata[key] print( ' {key}: {value}' .format_map(locals())) def argument_package_name(value): """ Check if an argument is a valid package name. Used as a ``type`` callback in ``add_argument()`` calls. Package names starting with a dash must be prefixed with a space to avoid collisions with command line arguments. :param str value: The command line argument :returns: The package name :raises argparse.ArgumentTypeError: if the value starts with a dash """ if value.startswith('-'): raise argparse.ArgumentTypeError('unrecognized argument: ' + value) return value.lstrip() colcon-package-information-0.4.0/colcon_package_information/verb/list.py000066400000000000000000000153241457437444000265450ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from colcon_core.command import get_prog_name from colcon_core.package_selection import add_arguments \ as add_packages_arguments from colcon_core.package_selection import get_package_descriptors from colcon_core.package_selection import select_package_decorators from colcon_core.plugin_system import satisfies_version from colcon_core.topological_order import topological_order_packages from colcon_core.verb import VerbExtensionPoint class ListVerb(VerbExtensionPoint): """List packages, optionally in topological ordering.""" def __init__(self): # noqa: D107 super().__init__() satisfies_version(VerbExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def add_arguments(self, *, parser): # noqa: D102 # only added so that package selection arguments can be used # which use the build directory to store state information parser.add_argument( '--build-base', default='build', help='The base path for all build directories (default: build)') add_packages_arguments(parser) parser.add_argument( '--topological-order', '-t', action='store_true', default=False, help='Order output based on topological ordering (breadth-first)') group = parser.add_mutually_exclusive_group() group.add_argument( '--names-only', '-n', action='store_true', default=False, help='Output only the name of each package but not the path') group.add_argument( '--paths-only', '-p', action='store_true', default=False, help='Output only the path of each package but not the name') group = parser.add_argument_group('Obsolete arguments') command_name = get_prog_name() self._add_obsolete_argument( group, '--topological-graph', '-g', action='store_true', default=False, help='Instead use `{command_name} graph`'.format_map(locals())) self._add_obsolete_argument( group, '--topological-graph-dot', action='store_true', default=False, help='Instead use `{command_name} graph --dot`' .format_map(locals())) self._add_obsolete_argument( group, '--topological-graph-density', action='store_true', default=False, help='Instead use `{command_name} graph --density`' .format_map(locals())) self._add_obsolete_argument( group, '--topological-graph-legend', action='store_true', default=False, help='Instead use `{command_name} graph --legend`' .format_map(locals())) self._add_obsolete_argument( group, '--topological-graph-dot-cluster', action='store_true', default=False, help='Instead use `{command_name} graph --dot --dot-cluster`' .format_map(locals())) self._add_obsolete_argument( group, '--topological-graph-dot-include-skipped', action='store_true', default=False, help='Instead use `{command_name} graph --dot ' '--dot-include-skipped`'.format_map(locals())) def _add_obsolete_argument(self, group, *args, **kwargs): arg = group.add_argument(*args, **kwargs) try: from argcomplete.completers import SuppressCompleter except ImportError: pass else: arg.completer = SuppressCompleter() return arg def main(self, *, context): # noqa: D102 args = context.args descriptors = get_package_descriptors(args) # always perform topological order for the select package extensions decorators = topological_order_packages( descriptors, recursive_categories=('run', )) select_package_decorators(args, decorators) if args.topological_graph or args.topological_graph_dot: additional_options = [] if args.topological_graph_dot: if args.topological_graph_dot_cluster: additional_options.append('--dot-cluster') if args.topological_graph_dot_include_skipped: additional_options.append('--dot-include-skipped') elif args.topological_graph_density: additional_options.append('--density') if args.topological_graph_legend: additional_options.append('--legend') additional_options = ''.join(' ' + x for x in additional_options) if args.topological_graph: return 'The {args.verb_name} options --topological-graph / -g ' \ 'are obsolete, instead use `{context.command_name} graph' \ '{additional_options}`'.format_map(locals()) if args.topological_graph_dot: return 'The {args.verb_name} option --topological-graph-dot is ' \ 'obsolete, instead use `{context.command_name} graph --dot' \ '{additional_options}`'.format_map(locals()) if args.topological_graph_density: return 'The option --topological-graph-density must be used ' \ 'together with --topological-graph' if args.topological_graph_legend: return 'The option --topological-graph-legend must be used ' \ ' with either --topological-graph or --topological-graph-dot' if args.topological_graph_dot_cluster: return 'The option --topological-graph-dot-cluster must be used ' \ 'together with --topological-graph-dot' if args.topological_graph_dot_include_skipped: return 'The option --topological-graph-dot-include-skipped must ' \ 'be used together with --topological-graph-dot' if not args.topological_order: decorators = sorted( decorators, key=lambda d: d.descriptor.name) lines = [] for decorator in decorators: if not decorator.selected: continue pkg = decorator.descriptor if args.names_only: lines.append(pkg.name) elif args.paths_only: lines.append(str(pkg.path)) else: lines.append( pkg.name + '\t' + str(pkg.path) + '\t(%s)' % pkg.type) if not args.topological_order: # output names and / or paths in alphabetical order lines.sort() for line in lines: print(line) colcon-package-information-0.4.0/publish-python.yaml000066400000000000000000000005201457437444000225660ustar00rootroot00000000000000artifacts: - type: wheel uploads: - type: pypi - type: stdeb uploads: - type: packagecloud config: repository: dirk-thomas/colcon distributions: - ubuntu:focal - ubuntu:jammy - ubuntu:noble - debian:bookworm - debian:trixie colcon-package-information-0.4.0/setup.cfg000066400000000000000000000044511457437444000205450ustar00rootroot00000000000000[metadata] name = colcon-package-information version = attr: colcon_package_information.__version__ url = https://colcon.readthedocs.io project_urls = Changelog = https://github.com/colcon/colcon-package-information/milestones?direction=desc&sort=due_date&state=closed GitHub = https://github.com/colcon/colcon-package-information/ 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 output package information. long_description = file: README.rst keywords = colcon [options] python_requires = >=3.6 install_requires = colcon-core>=0.5.2 packaging packages = find: zip_safe = true [options.extras_require] test = 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 [tool:pytest] filterwarnings = error # Suppress deprecation warnings in other packages ignore:lib2to3 package is deprecated::scspell ignore:pkg_resources is deprecated as an API::flake8_import_order ignore:SelectableGroups dict interface is deprecated::flake8 ignore:Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated::pyreadline junit_suite_name = colcon-package-information markers = flake8 linter [options.entry_points] colcon_core.package_augmentation = check_dependency_constraint = colcon_package_information.package_augmentation.check_dependency_constraint:CheckDependencyConstraintPackageAugmentation colcon_core.verb = graph = colcon_package_information.verb.graph:GraphVerb info = colcon_package_information.verb.info:InfoVerb list = colcon_package_information.verb.list:ListVerb [flake8] import-order-style = google [coverage:run] source = colcon_package_information colcon-package-information-0.4.0/setup.py000066400000000000000000000001721457437444000204320ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from setuptools import setup setup() colcon-package-information-0.4.0/stdeb.cfg000066400000000000000000000002501457437444000204770ustar00rootroot00000000000000[colcon-package-information] No-Python2: Depends3: python3-colcon-core (>= 0.5.2), python3-packaging Suite: focal jammy noble bookworm trixie X-Python3-Version: >= 3.6 colcon-package-information-0.4.0/test/000077500000000000000000000000001457437444000176775ustar00rootroot00000000000000colcon-package-information-0.4.0/test/spell_check.words000066400000000000000000000003621457437444000232340ustar00rootroot00000000000000apache argcomplete argparse colcon commonpath completers decos defaultdict deps descs fontcolor graphname iterdir itertools linter ljust lstrip nargs noqa pathlib plugin pydocstyle pytest rdep scspell setuptools subgraph thomas tpng unittest colcon-package-information-0.4.0/test/test_check_dependency_constraint.py000066400000000000000000000067751457437444000270460ustar00rootroot00000000000000# Copyright 2024 Open Source Robotics Foundation, Inc. # Licensed under the Apache License, Version 2.0 from unittest.mock import patch from colcon_core.dependency_descriptor import DependencyDescriptor from colcon_core.package_descriptor import PackageDescriptor from colcon_package_information.package_augmentation.\ check_dependency_constraint \ import CheckDependencyConstraintPackageAugmentation import pytest @pytest.mark.parametrize( 'operator,expect_lt,expect_eq,expect_gt', [ (None, 0, 0, 0), ('version_eq', 1, 0, 1), ('version_gt', 1, 1, 0), ('version_gte', 1, 0, 0), ('version_lt', 0, 1, 1), ('version_lte', 0, 0, 1), ('version_neq', 0, 1, 0), ]) def test_operators(operator, expect_lt, expect_eq, expect_gt): pkg_a_v1 = PackageDescriptor('/tmp/pkg_a') pkg_a_v1.name = 'pkg_a' pkg_a_v1.metadata['version'] = '1.0' pkg_a_v2 = PackageDescriptor('/tmp/pkg_a') pkg_a_v2.name = 'pkg_a' pkg_a_v2.metadata['version'] = '2.0' pkg_a_v3 = PackageDescriptor('/tmp/pkg_a') pkg_a_v3.name = 'pkg_a' pkg_a_v3.metadata['version'] = '3.0' pkg_a_dep = DependencyDescriptor('pkg_a') if operator is not None: pkg_a_dep.metadata[operator] = '2.0' pkg_b = PackageDescriptor('/tmp/pkg_b') pkg_b.name = 'pkg_b' pkg_b.dependencies['build'] = {pkg_a_dep} extension = CheckDependencyConstraintPackageAugmentation() with patch( 'colcon_package_information.package_augmentation.' 'check_dependency_constraint.logger.warning' ) as warning: extension.augment_packages({pkg_a_v1, pkg_b}) assert expect_lt == warning.call_count warning.reset_mock() extension.augment_packages({pkg_a_v2, pkg_b}) assert expect_eq == warning.call_count warning.reset_mock() extension.augment_packages({pkg_a_v3, pkg_b}) assert expect_gt == warning.call_count warning.reset_mock() def test_dependency_missing(): pkg_b = PackageDescriptor('/tmp/pkg_b') pkg_b.name = 'pkg_b' pkg_b.dependencies['build'] = { DependencyDescriptor('pkg_a'), } extension = CheckDependencyConstraintPackageAugmentation() extension.augment_packages({pkg_b}) def test_dependency_missing_version(): pkg_a = PackageDescriptor('/tmp/pkg_a') pkg_a.name = 'pkg_a' pkg_b = PackageDescriptor('/tmp/pkg_b') pkg_b.name = 'pkg_b' pkg_b.dependencies['build'] = { DependencyDescriptor('pkg_a'), } extension = CheckDependencyConstraintPackageAugmentation() extension.augment_packages({pkg_a, pkg_b}) def test_dependency_invalid_version(): pkg_a = PackageDescriptor('/tmp/pkg_a') pkg_a.name = 'pkg_a' pkg_a.metadata['version'] = 'totally!invalid&version' pkg_b = PackageDescriptor('/tmp/pkg_b') pkg_b.name = 'pkg_b' pkg_b.dependencies['build'] = { DependencyDescriptor('pkg_a'), } extension = CheckDependencyConstraintPackageAugmentation() extension.augment_packages({pkg_a, pkg_b}) def test_dependency_invalid_version_operator(): pkg_a = PackageDescriptor('/tmp/pkg_a') pkg_a.name = 'pkg_a' pkg_a.metadata['version'] = '2.0' pkg_b = PackageDescriptor('/tmp/pkg_b') pkg_b.name = 'pkg_b' pkg_b.dependencies['build'] = { DependencyDescriptor('pkg_a', metadata={ 'version_eq': 'totally!invalid&version' }), } extension = CheckDependencyConstraintPackageAugmentation() extension.augment_packages({pkg_a, pkg_b}) colcon-package-information-0.4.0/test/test_copyright_license.py000066400000000000000000000024731457437444000250300ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from pathlib import Path import sys import pytest @pytest.mark.linter 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(filter( lambda line: line.startswith('# Copyright'), lines)) 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-package-information-0.4.0/test/test_flake8.py000066400000000000000000000033521457437444000224650ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import logging from pathlib import Path import sys import pytest @pytest.mark.flake8 @pytest.mark.linter def test_flake8(): from flake8.api.legacy import get_style_guide # avoid debug / info / warning messages from flake8 internals logging.getLogger('flake8').setLevel(logging.ERROR) # for some reason the pydocstyle logger changes to an effective level of 1 # set higher level to prevent the output to be flooded with debug messages logging.getLogger('pydocstyle').setLevel(logging.WARNING) 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_package_information'), ]) 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(f'flake8 reported {total_errors} errors', file=sys.stderr) assert not total_errors, f'flake8 reported {total_errors} errors' colcon-package-information-0.4.0/test/test_spell_check.py000066400000000000000000000036271457437444000235740ustar00rootroot00000000000000# Copyright 2016-2019 Dirk Thomas # Licensed under the Apache License, Version 2.0 from pathlib import Path import pytest 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() @pytest.mark.linter def test_spell_check(known_words): from scspell import Report from scspell import SCSPELL_BUILTIN_DICT from scspell import spell_check source_filenames = [Path(__file__).parents[1] / 'setup.py'] + \ list( (Path(__file__).parents[1] / 'colcon_package_information') .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, \ f'Found {unknown_word_count} unknown words: ' + \ ', '.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, \ f'{unused_known_word_count} words in the word list are not used: ' + \ ', '.join(sorted(unused_known_words)) @pytest.mark.linter def test_spell_check_word_list_order(known_words): assert known_words == sorted(known_words), \ 'The word list should be ordered alphabetically' @pytest.mark.linter def test_spell_check_word_list_duplicates(known_words): assert len(known_words) == len(set(known_words)), \ 'The word list should not contain duplicates'