Skip to content
Merged
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__pycache__
17 changes: 17 additions & 0 deletions ros2cli/completion/ros2-argcomplete.bash
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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.

if type register-python-argcomplete > /dev/null 2>&1; then
eval "$(register-python-argcomplete ros2)"
fi
20 changes: 20 additions & 0 deletions ros2cli/package.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format2.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="2">
<name>ros2cli</name>
<version>0.0.0</version>
<description>
Framework for ROS 2 command line tools.
</description>
<maintainer email="[email protected]">Dirk Thomas</maintainer>
<license>Apache License 2.0</license>

<exec_depend>rclpy</exec_depend>

<test_depend>ament_copyright</test_depend>
<test_depend>ament_flake8</test_depend>

<export>
<build_type>ament_python</build_type>
</export>
</package>
Empty file added ros2cli/ros2cli/__init__.py
Empty file.
69 changes: 69 additions & 0 deletions ros2cli/ros2cli/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Copyright 2016-2017 Dirk Thomas

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are your copyrights in here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the code was written by me in my spare time for a different project.

# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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.

import argparse
import signal

from ros2cli.command import add_subparsers
from ros2cli.command import get_command_extensions


def main(*, script_name='ros2', argv=None, description=None, extension=None):
if description is None:
description = '{script_name} is an extensible command-line tool for ' \
'ROS 2.'.format_map(locals())

# top level parser
parser = argparse.ArgumentParser(
description=description,
formatter_class=argparse.RawDescriptionHelpFormatter
)

# add arguments for command extension(s)
if extension:
extension.add_arguments(parser, script_name)
else:
# get command extensions
extensions = get_command_extensions('ros2cli.command')
selected_extension_key = '_command'
add_subparsers(
parser, script_name, selected_extension_key, extensions,
# hide the special commands in the help
hide_extensions=['extension_points', 'extensions'])

# register argcomplete hook if available
try:
from argcomplete import autocomplete
except ImportError:
pass
else:
autocomplete(parser)

# parse the command line arguments
args = parser.parse_args(args=argv)

if extension is None:
# the attribute should always exist
# otherwise argparse should have exited
extension = getattr(args, selected_extension_key)

# call the main method of the extension
try:
rc = extension.main(parser=parser, args=args)
except KeyboardInterrupt:
rc = signal.SIGINT
except RuntimeError as e:
rc = str(e)
return rc
111 changes: 111 additions & 0 deletions ros2cli/ros2cli/command/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# Copyright 2016-2017 Dirk Thomas
# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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.

import argparse

from ros2cli.entry_points import get_first_line_doc
from ros2cli.plugin_system import instantiate_extensions
from ros2cli.plugin_system import PLUGIN_SYSTEM_VERSION
from ros2cli.plugin_system import satisfies_version


class CommandExtension(object):
"""
The extension point for 'command' extensions.

The following properties must be defined:
* `NAME` (will be set to the entry point name)

The following methods must be defined:
* `main`

The following methods can be defined:
* `add_arguments`
"""

NAME = None
EXTENSION_POINT_VERSION = '0.1'

def __init__(self):
super(CommandExtension, self).__init__()
satisfies_version(PLUGIN_SYSTEM_VERSION, '^0.1')

def add_arguments(self, parser, cli_name):
pass

def main(self, *, parser, args):
raise NotImplementedError()


def get_command_extensions(group_name):
extensions = instantiate_extensions(group_name)
for name, extension in extensions.items():
extension.NAME = name
return extensions


def add_subparsers(
parser, cli_name, dest, command_extensions, hide_extensions=None
):
"""
Create argparse subparser for each extension.

The ``cli_name`` is used for the title and description of the
``add_subparsers`` function call.

For each extension a subparser is created.
If the extension has an ``add_arguments`` method it is being called.

:param parser: the parent argument parser
:type parser: :py:class:`argparse.ArgumentParser`
:param str cli_name: name of the command line command to which the
subparsers are being added
:param str dest: name of the attribute under which the selected extension
will be stored
:param dict command_extensions: dict of command extensions by their name
where each contributes a command with specific arguments
"""
# add subparser with description of available subparsers
description = ''
if command_extensions:
max_length = max([
len(name) for name in command_extensions.keys()
if hide_extensions is None or name not in hide_extensions])
for name in sorted(command_extensions.keys()):
if hide_extensions is not None and name in hide_extensions:
continue
extension = command_extensions[name]
description += '%s %s\n' % (
name.ljust(max_length), get_first_line_doc(extension))
metavar = 'Call `{cli_name} <command> -h` for more detailed ' \
'usage.'.format_map(locals())
subparser = parser.add_subparsers(
title='Commands', description=description, metavar=metavar)
# use a name which doesn't collide with any argument
# but is readable when shown as part of the the usage information
subparser.dest = ' ' + dest.lstrip('_')
subparser.required = True

# add extension specific sub-parser with its arguments
for name in sorted(command_extensions.keys()):
extension = command_extensions[name]
command_parser = subparser.add_parser(
extension.NAME,
description=get_first_line_doc(extension),
formatter_class=argparse.RawDescriptionHelpFormatter)
command_parser.set_defaults(**{dest: extension})
if hasattr(extension, 'add_arguments'):
extension.add_arguments(
command_parser, '{cli_name} {name}'.format_map(locals()))
68 changes: 68 additions & 0 deletions ros2cli/ros2cli/command/extension_points.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Copyright 2016-2017 Dirk Thomas
# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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.

from ros2cli.command import CommandExtension
from ros2cli.entry_points import EXTENSION_POINT_GROUP_NAME
from ros2cli.entry_points import get_entry_points
from ros2cli.entry_points import get_first_line_doc


class ExtensionPointsCommand(CommandExtension):
"""List extension points."""

def add_arguments(self, parser, cli_name):
parser.add_argument(
'--all', '-a',
action='store_true',
default=False,
help='Also show extension points which failed to be imported. '
'(prefixed with `- `)')
parser.add_argument(
'--verbose', '-v',
action='store_true',
default=False,
help='Show more information for each extension point')

def main(self, *, parser, args):
extension_points = get_entry_points(EXTENSION_POINT_GROUP_NAME)
for name in sorted(extension_points.keys()):
self.print_extension_point(
args, name, extension_points[name])

def print_extension_point(self, args, name, entry_point):
exception = None
try:
extension_point = entry_point.load()
except Exception as e:
if not args.all:
# skip entry points which failed to load
return
exception = e
extension_point = None

prefix = '' if exception is None else '- '
print(prefix + name + ':', get_first_line_doc(extension_point))

if args.verbose:
print(prefix, ' ', 'module_name:', entry_point.module_name)
if entry_point.attrs:
print(prefix, ' ', 'attributes:', '.'.join(entry_point.attrs))
if hasattr(extension_point, 'EXTENSION_POINT_VERSION'):
print(
prefix, ' ', 'version:',
extension_point.EXTENSION_POINT_VERSION)

if exception:
print(prefix, ' ', 'reason:', str(exception))
75 changes: 75 additions & 0 deletions ros2cli/ros2cli/command/extensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Copyright 2016-2017 Dirk Thomas
# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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.

from ros2cli.command import CommandExtension
from ros2cli.entry_points import get_all_entry_points
from ros2cli.entry_points import get_first_line_doc


class ExtensionsCommand(CommandExtension):
"""List extensions."""

def add_arguments(self, parser, cli_name):
parser.add_argument(
'--all', '-a',
action='store_true',
default=False,
help='Also show extensions which failed to load or are '
'incompatible. (prefixed with `- `)')
parser.add_argument(
'--verbose', '-v',
action='store_true',
default=False,
help='Show more information for each extension')

def main(self, *, parser, args):
all_entry_points = get_all_entry_points()
for group_name in sorted(all_entry_points.keys()):
print(group_name)
group = all_entry_points[group_name]
for entry_point_name in sorted(group.keys()):
(dist, entry_point) = group[entry_point_name]
self.print_entry_point(args, dist, entry_point)

def print_entry_point(self, args, dist, entry_point):
exception = None
try:
plugin = entry_point.load()
except Exception as e:
if not args.all:
# skip entry points which failed to load
return
exception = e
plugin = None
else:
try:
plugin()
except Exception as e:
if not args.all:
# skip plugins which failed to be instantiated
return
exception = e

prefix = ' ' if exception is None else '-'
print(prefix, entry_point.name + ':', get_first_line_doc(plugin))

if args.verbose:
print(prefix, ' ', 'module_name:', entry_point.module_name)
if entry_point.attrs:
print(prefix, ' ', 'attributes:', '.'.join(entry_point.attrs))
print(prefix, ' ', 'distribution:', repr(dist))

if exception:
print(prefix, ' ', 'reason:', str(exception))
Loading