├── .github
└── workflows
│ └── python-test.yml
├── .gitignore
├── CHANGELOG.rst
├── CMakeLists.txt
├── LICENSE
├── MANIFEST.in
├── README.rst
├── bin
└── rosidl_generator_mypy
├── cmake
├── custom_command.cmake
├── register_mypy.cmake
└── rosidl_generator_mypy_generate_interfaces.cmake
├── package.xml
├── pyproject.toml
├── requirements.dev.txt
├── resource
├── _action.pyi.em
├── _idl.pyi.em
├── _imports.pyi.em
├── _msg.pyi.em
└── _srv.pyi.em
├── rosidl_generator_mypy-extras.cmake.in
├── rosidl_generator_mypy
├── __init__.py
├── cli.py
└── py.typed
├── setup.cfg
└── setup.py
/.github/workflows/python-test.yml:
--------------------------------------------------------------------------------
1 | name: Python tests
2 | on:
3 | push:
4 | branches:
5 | - master
6 | pull_request: {}
7 | jobs:
8 | lint:
9 | name: Run lint
10 | runs-on: ubuntu-20.04
11 | timeout-minutes: 15
12 | steps:
13 | - uses: actions/checkout@v2
14 | with:
15 | lfs: false
16 | - uses: actions/setup-python@v4
17 | with:
18 | python-version: '3.10'
19 | - name: Create venv
20 | run: |
21 | python -m venv venv
22 | source venv/bin/activate
23 | pip install -r requirements.dev.txt
24 | - name: Run pysen
25 | run: |
26 | source venv/bin/activate
27 | pysen run lint
28 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.swp
2 |
3 | *.egg-info/
4 | *.py[cod]
5 | .cache
6 | .mypy_cache/
7 | .tox/
8 | __pycache__/
9 | build/
10 | dist/
11 | pip-wheel-metadata/
12 | venv/
13 |
--------------------------------------------------------------------------------
/CHANGELOG.rst:
--------------------------------------------------------------------------------
1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 | Changelog for package rosidl_generator_mypy
3 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4 |
5 | 0.1.0 (2021-05-10)
6 | ------------------
7 | * Initial release
8 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.5)
2 |
3 | project(rosidl_generator_mypy)
4 |
5 | find_package(ament_cmake REQUIRED)
6 | find_package(ament_cmake_python REQUIRED)
7 | find_package(rosidl_cmake REQUIRED)
8 | find_package(rosidl_generator_py REQUIRED)
9 |
10 | ament_export_dependencies(ament_cmake)
11 | ament_export_dependencies(rmw)
12 | ament_export_dependencies(rosidl_cmake)
13 | ament_export_dependencies(rosidl_generator_py)
14 |
15 | ament_index_register_resource("rosidl_generator_packages")
16 |
17 | ament_python_install_package(${PROJECT_NAME})
18 |
19 | ament_package(
20 | CONFIG_EXTRAS "cmake/register_mypy.cmake"
21 | "rosidl_generator_mypy-extras.cmake.in"
22 | )
23 |
24 | install(
25 | PROGRAMS bin/rosidl_generator_mypy
26 | DESTINATION lib/rosidl_generator_mypy
27 | )
28 | install(
29 | DIRECTORY cmake resource
30 | DESTINATION share/${PROJECT_NAME}
31 | )
32 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | Copyright 2021 Yuki Igarashi, Tamaki Nishino
179 |
180 | Licensed under the Apache License, Version 2.0 (the "License");
181 | you may not use this file except in compliance with the License.
182 | You may obtain a copy of the License at
183 |
184 | http://www.apache.org/licenses/LICENSE-2.0
185 |
186 | Unless required by applicable law or agreed to in writing, software
187 | distributed under the License is distributed on an "AS IS" BASIS,
188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189 | See the License for the specific language governing permissions and
190 | limitations under the License.
191 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include CMakeLists.txt
2 | include LICENSE
3 | include README.rst
4 | include bin/rosidl_generator_mypy
5 | include package.xml
6 | include rosidl_generator_mypy-extras.cmake.in
7 |
8 | recursive-include cmake *.cmake
9 | recursive-include resource *.cmake *.em
10 | recursive-include rosidl_generator_mypy *.py py.typed
11 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | =====================
2 | rosidl_generator_mypy
3 | =====================
4 |
5 | Stub files generator for the ROS2 interfaces in Python
6 |
7 | Installation
8 | ============
9 |
10 | .. code:: sh
11 |
12 | cd your_workspace/src
13 | git clone https://github.com/rospypi/rosidl_generator_mypy.git
14 |
15 |
16 | Usage
17 | =====
18 |
19 | Add ``rosidl_generator_mypy`` to your ``CMakeLists.txt``.
20 | This package will be registered as a ``rosidl_generate_idl_interfaces`` extension
21 | so that ``rosidl`` automatically find and call this library when ``rosidl_generate_interfaces`` is called.
22 |
23 | Also, keep in mind that your package should have the build dependency
24 | for ``rosidl_generator_mypy`` in ``package.xml`` to make sure that the build tool finishes the
25 | build of ``rosidl_generator_mypy`` before building your package.
26 |
27 | Examples:
28 |
29 | - CMakeLists.txt
30 | .. code:: cmake
31 |
32 | find_package(rosidl_generator_mypy REQUIRED)
33 | - package.xml
34 | .. code:: xml
35 |
36 | rosidl_generator_mypy
37 |
--------------------------------------------------------------------------------
/bin/rosidl_generator_mypy:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import argparse
4 | import os
5 | import pathlib
6 | import sys
7 |
8 | try:
9 | from rosidl_generator_mypy import generate
10 | except ImportError:
11 | # NOTE: Modifying sys.path and importing the Python package with the same
12 | # name as this script does not work on Windows
13 | # Use the same way as:
14 | # https://github.com/ros2/rosidl_python/blob/5b9fe9cad6876e877cbbcf17950c47a9e753c6e6/rosidl_generator_py/bin/rosidl_generator_py#L10-L21 # NOQA
15 | module_name = "rosidl_generator_mypy"
16 | root_path = pathlib.Path(__file__).resolve().parents[1]
17 | init_path = os.path.join(root_path, "rosidl_generator_mypy", "__init__.py")
18 | if not os.path.exists(init_path):
19 | raise FileNotFoundError("{} doesn't exist".format(init_path))
20 |
21 | from importlib.machinery import SourceFileLoader
22 |
23 | loader = SourceFileLoader(module_name, init_path)
24 | rosidl_generator_mypy = loader.load_module()
25 | generate = rosidl_generator_mypy.generate
26 |
27 |
28 | def main(argv=sys.argv[1:]):
29 | parser = argparse.ArgumentParser(
30 | description="Generate stub files for the Python ROS interfaces."
31 | )
32 | parser.add_argument(
33 | "--generator-arguments-file",
34 | required=True,
35 | help="The location of the file containing the generator arguments",
36 | )
37 | args = parser.parse_args(argv)
38 |
39 | generate(args.generator_arguments_file)
40 | return 0
41 |
42 |
43 | if __name__ == "__main__":
44 | sys.exit(main())
45 |
--------------------------------------------------------------------------------
/cmake/custom_command.cmake:
--------------------------------------------------------------------------------
1 | add_custom_command(
2 | OUTPUT ${_generated_pyi_files}
3 | COMMAND ${PYTHON_EXECUTABLE} ${rosidl_generator_mypy_BIN}
4 | --generator-arguments-file "${generator_arguments_file}"
5 | DEPENDS ${target_dependencies} ${rosidl_generate_interfaces_TARGET}
6 | COMMENT "Generating Python stub for ROS interfaces"
7 | VERBATIM
8 | )
9 |
10 | if(TARGET ${rosidl_generate_interfaces_TARGET}${_target_suffix})
11 | message(WARNING "Custom target ${rosidl_generate_interfaces_TARGET}${_target_suffix} already exists")
12 | else()
13 | add_custom_target(
14 | ${rosidl_generate_interfaces_TARGET}${_target_suffix} ALL
15 | DEPENDS
16 | ${_generated_pyi_files}
17 | )
18 | endif()
19 |
--------------------------------------------------------------------------------
/cmake/register_mypy.cmake:
--------------------------------------------------------------------------------
1 | macro(rosidl_generator_mypy_extras BIN GENERATOR_FILES TEMPLATE_DIR)
2 | find_package(ament_cmake_core QUIET REQUIRED)
3 | # This idl generator must run after rosidl_generator_py runs
4 | find_package(rosidl_generator_py QUIET REQUIRED)
5 |
6 | ament_register_extension(
7 | "rosidl_generate_idl_interfaces"
8 | "rosidl_generator_mypy"
9 | "rosidl_generator_mypy_generate_interfaces.cmake")
10 |
11 | normalize_path(BIN "${BIN}")
12 | set(rosidl_generator_mypy_BIN "${BIN}")
13 |
14 | set(rosidl_generator_mypy_GENERATOR_FILES "")
15 | foreach(_generator_file ${GENERATOR_FILES})
16 | normalize_path(_generator_file "${_generator_file}")
17 | list(APPEND rosidl_generator_mypy_GENERATOR_FILES "${_generator_file}")
18 | endforeach()
19 |
20 | normalize_path(TEMPLATE_DIR "${TEMPLATE_DIR}")
21 | set(rosidl_generator_mypy_TEMPLATE_DIR "${TEMPLATE_DIR}")
22 | endmacro()
23 |
--------------------------------------------------------------------------------
/cmake/rosidl_generator_mypy_generate_interfaces.cmake:
--------------------------------------------------------------------------------
1 | find_package(rmw REQUIRED)
2 |
3 | find_package(Python3 REQUIRED COMPONENTS Interpreter)
4 |
5 | set(_output_path
6 | "${CMAKE_CURRENT_BINARY_DIR}/rosidl_generator_mypy/${PROJECT_NAME}")
7 | set(_generated_pyi_files "")
8 |
9 | # list the file names of generated pyi
10 | foreach(_abs_idl_file ${rosidl_generate_interfaces_ABS_IDL_FILES})
11 | get_filename_component(_parent_folder "${_abs_idl_file}" DIRECTORY)
12 | get_filename_component(_parent_folder "${_parent_folder}" NAME)
13 | get_filename_component(_idl_name "${_abs_idl_file}" NAME_WE)
14 | string_camel_case_to_lower_case_underscore("${_idl_name}" _module_name)
15 | list(APPEND _generated_pyi_files
16 | "${_output_path}/${_parent_folder}/_${_module_name}.pyi")
17 | endforeach()
18 |
19 | # create pyi and py.typed to mark package PEP561 compatible
20 | file(MAKE_DIRECTORY "${_output_path}")
21 | file(WRITE "${_output_path}/__init__.pyi" "")
22 | file(WRITE "${_output_path}/py.typed" "")
23 |
24 | # NOTE: create a list of directories that have one or more pyi files
25 | # Also add `__init__.pyi` of each package directory to `_generated_pyi_files`
26 | # See: https://github.com/ros2/rosidl_python/blob/5b9fe9cad6876e877cbbcf17950c47a9e753c6e6/rosidl_generator_py/cmake/rosidl_generator_py_generate_interfaces.cmake#L57-L72
27 | set(_generated_pyi_dirs "")
28 | foreach(_generated_pyi_file ${_generated_pyi_files})
29 | get_filename_component(_parent_folder "${_generated_pyi_file}" DIRECTORY)
30 | set(_init_module "${_parent_folder}/__init__.pyi")
31 | list(FIND _generated_pyi_files "${_init_module}" _index)
32 | if(_index EQUAL -1)
33 | list(APPEND _generated_pyi_files "${_init_module}")
34 |
35 | string(LENGTH "${_output_path}" _length)
36 | math(EXPR _index "${_length} + 1")
37 | string(SUBSTRING "${_parent_folder}" ${_index} -1 _relative_directory)
38 | list(APPEND _generated_pyi_dirs "${_relative_directory}")
39 | endif()
40 | endforeach()
41 |
42 | # get a list of dependency files of idl files to set target_dependencies properly
43 | set(_dependency_files "")
44 | set(_dependencies "")
45 | foreach(_pkg_name ${rosidl_generate_interfaces_DEPENDENCY_PACKAGE_NAMES})
46 | foreach(_idl_file ${${_pkg_name}_IDL_FILES})
47 | set(_abs_idl_file "${${_pkg_name}_DIR}/../${_idl_file}")
48 | normalize_path(_abs_idl_file "${_abs_idl_file}")
49 | list(APPEND _dependency_files "${_abs_idl_file}")
50 | list(APPEND _dependencies "${_pkg_name}:${_abs_idl_file}")
51 | endforeach()
52 | endforeach()
53 |
54 | set(target_dependencies
55 | "${rosidl_generator_mypy_BIN}"
56 | ${rosidl_generator_mypy_GENERATOR_FILES}
57 | "${rosidl_generator_mypy_TEMPLATE_DIR}/_action.pyi.em"
58 | "${rosidl_generator_mypy_TEMPLATE_DIR}/_idl.pyi.em"
59 | "${rosidl_generator_mypy_TEMPLATE_DIR}/_imports.pyi.em"
60 | "${rosidl_generator_mypy_TEMPLATE_DIR}/_msg.pyi.em"
61 | "${rosidl_generator_mypy_TEMPLATE_DIR}/_srv.pyi.em"
62 | ${rosidl_generate_interfaces_ABS_IDL_FILES}
63 | ${_dependency_files})
64 | foreach(dep ${target_dependencies})
65 | if(NOT EXISTS "${dep}")
66 | message(FATAL_ERROR "Target dependency '${dep}' does not exist")
67 | endif()
68 | endforeach()
69 |
70 | # write build arguments into a json, then pass the file to our script
71 | set(generator_arguments_file "${CMAKE_CURRENT_BINARY_DIR}/rosidl_generator_mypy__arguments.json")
72 | rosidl_write_generator_arguments(
73 | "${generator_arguments_file}"
74 | PACKAGE_NAME "${PROJECT_NAME}"
75 | IDL_TUPLES "${rosidl_generate_interfaces_IDL_TUPLES}"
76 | ROS_INTERFACE_DEPENDENCIES "${_dependencies}"
77 | OUTPUT_DIR "${_output_path}"
78 | TEMPLATE_DIR "${rosidl_generator_mypy_TEMPLATE_DIR}"
79 | TARGET_DEPENDENCIES ${target_dependencies}
80 | )
81 |
82 | if(NOT rosidl_generate_interfaces_SKIP_INSTALL)
83 | # NOTE: This generator depends on rosidl_generator_py for creating module directory.
84 | # As `ament_python_install_module` is not supposed to be called multiple times,
85 | # we have encountered the same problem as:
86 | # https://github.com/ros2/rosidl/issues/88 and https://github.com/ros2/rosidl/pull/89
87 | install(FILES "${_output_path}/__init__.pyi" "${_output_path}/py.typed"
88 | DESTINATION "${PYTHON_INSTALL_DIR}/${PROJECT_NAME}/${_generated_py_dir}"
89 | )
90 |
91 | foreach(_generated_py_dir ${_generated_pyi_dirs})
92 | install(DIRECTORY "${_output_path}/${_generated_py_dir}/"
93 | DESTINATION "${PYTHON_INSTALL_DIR}/${PROJECT_NAME}/${_generated_py_dir}"
94 | PATTERN "*.pyi"
95 | )
96 | endforeach()
97 | endif()
98 |
99 | set(_target_suffix "__mypy")
100 |
101 | # NOTE: See https://github.com/ros2/rosidl/issues/124 and https://github.com/ros2/rosidl/pull/135 for the
102 | # rationale behind the following logic. Use the same logic as the one in rosidl_python:
103 | # https://github.com/ros2/rosidl_python/blob/5b9fe9cad6876e877cbbcf17950c47a9e753c6e6/rosidl_generator_py/cmake/rosidl_generator_py_generate_interfaces.cmake#L146-L155
104 | set(_subdir "${CMAKE_CURRENT_BINARY_DIR}/${rosidl_generate_interfaces_TARGET}${_target_suffix}")
105 | file(MAKE_DIRECTORY "${_subdir}")
106 | file(READ "${rosidl_generator_mypy_DIR}/custom_command.cmake" _custom_command)
107 | file(WRITE "${_subdir}/CMakeLists.txt" "${_custom_command}")
108 | add_subdirectory("${_subdir}" ${rosidl_generate_interfaces_TARGET}${_target_suffix})
109 | set_property(
110 | SOURCE
111 | ${_generated_pyi_files}
112 | PROPERTY GENERATED 1)
113 |
114 | # list(APPEND ALL_OUTPUT_FILES_mypy ${GEN_OUTPUT_FILE})
115 |
--------------------------------------------------------------------------------
/package.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | rosidl_generator_mypy
5 | 0.1.0
6 | Generate stub files for the ROS2 interfaces in Python
7 | Yuki Igarashi
8 | Tamaki Nishino
9 | Apache License 2.0
10 | Yuki Igarashi
11 | Tamaki Nishino
12 |
13 | ament_cmake
14 | rosidl_cmake
15 | rosidl_generator_py
16 |
17 | ament_cmake
18 |
19 | rmw
20 |
21 | rosidl_cmake
22 | rosidl_generator_py
23 | rosidl_parser
24 |
25 | rmw
26 | rosidl_cmake
27 | rosidl_parser
28 |
29 | rosidl_generator_packages
30 |
31 |
32 | ament_cmake
33 |
34 |
35 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.pysen]
2 | version = "0.10"
3 |
4 | [tool.pysen.lint]
5 | enable_black = true
6 | enable_flake8 = true
7 | enable_isort = true
8 | enable_mypy = true
9 | mypy_preset = "strict"
10 | py_version = "py36"
11 | isort_known_first_party = ["rosidl_generator_mypy"]
12 | [tool.pysen.lint.source]
13 | includes = [".", "bin/rosidl_generator_mypy"]
14 | excludes = [".tox", "venv"]
15 | [[tool.pysen.lint.mypy_targets]]
16 | paths = ["."]
17 |
--------------------------------------------------------------------------------
/requirements.dev.txt:
--------------------------------------------------------------------------------
1 | black==22.12.0
2 | flake8==6.0.0
3 | isort==5.11.3
4 | mypy==0.991
5 | pysen==0.10.2
6 |
--------------------------------------------------------------------------------
/resource/_action.pyi.em:
--------------------------------------------------------------------------------
1 | @# Included from rosidl_generator_mypy/resource/_idl.py.em
2 | @{
3 | if generate_imports:
4 | from rosidl_generator_mypy import append_import_statements_action
5 |
6 | TEMPLATE(
7 | '_imports.pyi.em',
8 | component=action, defined_classes=defined_classes, generator=append_import_statements_action)
9 | }@
10 | @#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
11 | @{
12 | from rosidl_cmake import convert_camel_case_to_lower_case_underscore
13 |
14 | action_name = '_' + convert_camel_case_to_lower_case_underscore(action.namespaced_type.name)
15 | module_name = '_' + convert_camel_case_to_lower_case_underscore(interface_path.stem)
16 |
17 | TEMPLATE(
18 | '_msg.pyi.em',
19 | package_name=package_name, interface_path=interface_path,
20 | message=action.goal, generate_imports=False, defined_classes=defined_classes)
21 | TEMPLATE(
22 | '_msg.pyi.em',
23 | package_name=package_name, interface_path=interface_path,
24 | message=action.result, generate_imports=False, defined_classes=defined_classes)
25 | TEMPLATE(
26 | '_msg.pyi.em',
27 | package_name=package_name, interface_path=interface_path,
28 | message=action.feedback, generate_imports=False, defined_classes=defined_classes)
29 | TEMPLATE(
30 | '_srv.pyi.em',
31 | package_name=package_name, interface_path=interface_path,
32 | service=action.send_goal_service, generate_imports=False, defined_classes=defined_classes)
33 | TEMPLATE(
34 | '_srv.pyi.em',
35 | package_name=package_name, interface_path=interface_path,
36 | service=action.get_result_service, generate_imports=False, defined_classes=defined_classes)
37 | TEMPLATE(
38 | '_msg.pyi.em',
39 | package_name=package_name, interface_path=interface_path,
40 | message=action.feedback_message, generate_imports=False, defined_classes=defined_classes)
41 | }@
42 |
43 | class Metaclass_@(action.namespaced_type.name)(type):
44 | _TYPE_SUPPORT: typing.Any = ...
45 | @@classmethod
46 | def __import_type_support__(cls) -> None: ...
47 |
48 | @#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
49 | @{
50 |
51 | def assert_namespace_equals(action, structure):
52 | assert structure.namespaced_type.namespaces == action.namespaced_type.namespaces
53 |
54 | # Make sure that all requires messages in a single file
55 | assert_namespace_equals(action, action.goal.structure)
56 | assert_namespace_equals(action, action.result.structure)
57 | assert_namespace_equals(action, action.feedback.structure)
58 |
59 | # The namespace of the following messages must be same as the action as they are defined in rosidl_parser.definition
60 | # But we call assertions just to make sure the specification has not been changed
61 | assert_namespace_equals(action, action.send_goal_service)
62 | assert_namespace_equals(action, action.get_result_service)
63 | assert_namespace_equals(action, action.feedback_message.structure)
64 | # Then, emit member names without namespaces as follows
65 |
66 | }@
67 | @#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
68 | class @(action.namespaced_type.name)(metaclass=Metaclass_@(action.namespaced_type.name)):
69 | Goal: TypeAlias = @(action.goal.structure.namespaced_type.name)
70 | Result: TypeAlias = @(action.result.structure.namespaced_type.name)
71 | Feedback: TypeAlias = @(action.feedback.structure.namespaced_type.name)
72 |
73 | class Impl:
74 | SendGoalService: TypeAlias = @(action.send_goal_service.namespaced_type.name)
75 | GetResultService: TypeAlias = @(action.get_result_service.namespaced_type.name)
76 | FeedbackMessage: TypeAlias = @(action.feedback_message.structure.namespaced_type.name)
77 |
78 | from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService
79 | from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage
80 |
81 | def __init__(self) -> None: ...
82 |
--------------------------------------------------------------------------------
/resource/_idl.pyi.em:
--------------------------------------------------------------------------------
1 | # generated from rosidl_generator_mypy/resource/_idl.pyi.em
2 | # with input from @(package_name):@(interface_path)
3 | # generated code does not contain a copyright notice
4 |
5 | @
6 | @#######################################################################
7 | @# EmPy template for generating _.pyi files
8 | @#
9 | @# Context:
10 | @# - package_name (string)
11 | @# - interface_path (Path relative to the directory named after the package)
12 | @# - content (IdlContent, list of elements, e.g. Messages or Services)
13 | @#######################################################################
14 | @{
15 | from rosidl_generator_mypy import get_defined_classes
16 |
17 | defined_classes = get_defined_classes(content)
18 | }@
19 | @#######################################################################
20 | @# Handle messages
21 | @#######################################################################
22 | @{
23 | from rosidl_parser.definition import Message
24 | }@
25 | @[for message in content.get_elements_of_type(Message)]@
26 | @{
27 | TEMPLATE(
28 | '_msg.pyi.em',
29 | package_name=package_name, interface_path=interface_path, message=message,
30 | generate_imports=True, defined_classes=defined_classes)
31 | }@
32 | @[end for]@
33 | @
34 | @#######################################################################
35 | @# Handle services
36 | @#######################################################################
37 | @{
38 | from rosidl_parser.definition import Service
39 | }@
40 | @[for service in content.get_elements_of_type(Service)]@
41 | @{
42 | TEMPLATE(
43 | '_srv.pyi.em',
44 | package_name=package_name, interface_path=interface_path, service=service,
45 | generate_imports=True, defined_classes=defined_classes)
46 | }@
47 | @[end for]@
48 | @
49 | @#######################################################################
50 | @# Handle actions
51 | @#######################################################################
52 | @{
53 | from rosidl_parser.definition import Action
54 | }@
55 | @[for action in content.get_elements_of_type(Action)]@
56 | @{
57 | TEMPLATE(
58 | '_action.pyi.em',
59 | package_name=package_name, interface_path=interface_path, action=action,
60 | generate_imports=True, defined_classes=defined_classes)
61 | }@
62 | @[end for]@
63 |
--------------------------------------------------------------------------------
/resource/_imports.pyi.em:
--------------------------------------------------------------------------------
1 | @# Included from rosidl_generator_mypy/resource/*.pyi.em
2 | @{
3 | third_party_imports = set()
4 | first_party_imports = set()
5 | generator(component, defined_classes, third_party_imports, first_party_imports)
6 |
7 | }@
8 |
9 | import sys
10 | import typing
11 | if sys.version_info < (3, 10):
12 | from typing_extensions import TypeAlias
13 | else:
14 | from typing import TypeAlias
15 |
16 | import array
17 | import numpy as np
18 |
19 | @[if len(third_party_imports) > 0]@
20 |
21 | @[for statement in sorted(third_party_imports)]@
22 | @(statement)
23 | @[end for]@
24 | @[ end if]@
25 | @[if len(first_party_imports) > 0]@
26 |
27 | @[for statement in sorted(first_party_imports)]@
28 | @(statement)
29 | @[end for]@
30 | @[ end if]@
31 |
--------------------------------------------------------------------------------
/resource/_msg.pyi.em:
--------------------------------------------------------------------------------
1 | @# Included from rosidl_generator_mypy/resource/_idl.pyi.em
2 | @#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
3 | @{
4 | import builtins
5 | import inspect
6 |
7 | from rosidl_parser.definition import EMPTY_STRUCTURE_REQUIRED_MEMBER_NAME
8 |
9 | from rosidl_generator_mypy import to_type_annotation
10 |
11 | builtin_items = set(dict(inspect.getmembers(builtins)).keys())
12 | current_namespace = message.structure.namespaced_type
13 | members = []
14 | for member in message.structure.members:
15 | if len(message.structure.members) == 1 and member.name == EMPTY_STRUCTURE_REQUIRED_MEMBER_NAME:
16 | continue
17 |
18 | noqa_string = ''
19 | if member.name in builtin_items:
20 | noqa_string = ' # noqa: A003'
21 |
22 | members.append(
23 | (member.name, to_type_annotation(current_namespace, defined_classes, member.type), noqa_string)
24 | )
25 | }@
26 | @#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
27 | @{
28 | if generate_imports:
29 | from rosidl_generator_mypy import append_import_statements_msg
30 |
31 | # NOTE: No import statement is required for constants as we cannot use any NamespacedType
32 | TEMPLATE(
33 | '_imports.pyi.em',
34 | component=message, defined_classes=defined_classes, generator=append_import_statements_msg)
35 | }@
36 | @#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
37 |
38 | class Metaclass_@(message.structure.namespaced_type.name)(type):
39 | _CREATE_ROS_MESSAGE: typing.Any = ...
40 | _CONVERT_FROM_PY: typing.Any = ...
41 | _CONVERT_TO_PY: typing.Any = ...
42 | _DESTROY_ROS_MESSAGE: typing.Any = ...
43 | _TYPE_SUPPORT: typing.Any = ...
44 | __constants: typing.Dict[str, typing.Any] = ...
45 |
46 | @@classmethod
47 | def __import_type_support__(cls) -> None: ...
48 | @@classmethod
49 | def __prepare__(
50 | cls, __name: str, __bases: typing.Tuple[type, ...], **kwargs: typing.Any
51 | ) -> typing.MutableMapping[str, typing.Any]: ...
52 | @[for constant in message.constants]@
53 | @@property
54 | def @(constant.name)(self) -> @(to_type_annotation(current_namespace, defined_classes, constant.type).getter): ...
55 | @[end for]@
56 | @[for member in message.structure.members]@
57 | @[ if member.has_annotation('default')]@
58 | @@property
59 | def @(member.name.upper())__DEFAULT(cls) -> @(to_type_annotation(current_namespace, defined_classes, member.type).getter): ...
60 | @[ end if]@
61 | @[end for]@
62 |
63 | class @(message.structure.namespaced_type.name)(metaclass=Metaclass_@(message.structure.namespaced_type.name)):
64 | __slots__: typing.List[str] = ...
65 | _fields_and_field_types: typing.Dict[str, str] = ...
66 | SLOT_TYPES: typing.Tuple[rosidl_parser.definition.AbstractType, ...] = ...
67 |
68 | def __init__(
69 | self,
70 | @[if len(members)]@
71 | *,
72 | @[end if]@
73 | @[for name, annotation, noqa_string in members]@
74 | @(name): @(annotation.setter) = ...,@(noqa_string)
75 | @[end for]@
76 | **kwargs: typing.Any,
77 | ) -> None: ...
78 | def __repr__(self) -> str: ...
79 | def __eq__(self, other: typing.Any) -> bool: ...
80 | @@classmethod
81 | def get_fields_and_field_types(cls) -> typing.Dict[str, str]: ...
82 | # Members
83 | @[for name, annotation, noqa_string in members]@
84 | @@property@(noqa_string)
85 | def @(name)(self) -> @(annotation.getter): ...@(noqa_string)
86 | @@@(name).setter@(noqa_string)
87 | def @(name)(self, value: @(annotation.setter)) -> None: ...@(noqa_string)
88 | @[end for]@
89 |
--------------------------------------------------------------------------------
/resource/_srv.pyi.em:
--------------------------------------------------------------------------------
1 | @# Included from rosidl_generator_mypy/resource/_idl.py.em
2 | @{
3 | if generate_imports:
4 | from rosidl_generator_mypy import append_import_statements_srv
5 |
6 | TEMPLATE(
7 | '_imports.pyi.em',
8 | component=service, defined_classes=defined_classes, generator=append_import_statements_srv)
9 | }@
10 | @#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
11 | @{
12 | from rosidl_cmake import convert_camel_case_to_lower_case_underscore
13 |
14 | service_name = '_' + convert_camel_case_to_lower_case_underscore(service.namespaced_type.name)
15 | module_name = '_' + convert_camel_case_to_lower_case_underscore(interface_path.stem)
16 |
17 | TEMPLATE(
18 | '_msg.pyi.em',
19 | package_name=package_name, interface_path=interface_path,
20 | message=service.request_message, generate_imports=False,
21 | defined_classes=defined_classes)
22 | TEMPLATE(
23 | '_msg.pyi.em',
24 | package_name=package_name, interface_path=interface_path,
25 | message=service.response_message, generate_imports=False,
26 | defined_classes=defined_classes)
27 | }@
28 |
29 | class Metaclass_@(service.namespaced_type.name)(type):
30 | _TYPE_SUPPORT: typing.Any = ...
31 |
32 | @@classmethod
33 | def __import_type_support__(cls) -> None: ...
34 |
35 | @#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
36 | @{
37 | # Make sure that all requires messages in a single file
38 | assert service.request_message.structure.namespaced_type.namespaces == service.namespaced_type.namespaces
39 | assert service.response_message.structure.namespaced_type.namespaces == service.namespaced_type.namespaces
40 | # Then, emit member names without namespace for Request and Response as follows
41 | }@
42 | @#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
43 | class @(service.namespaced_type.name)(metaclass=Metaclass_@(service.namespaced_type.name)):
44 | Request: TypeAlias[@(service.request_message.structure.namespaced_type.name)] = @(service.request_message.structure.namespaced_type.name)
45 | Response: TypeAlias[@(service.response_message.structure.namespaced_type.name)] = @(service.response_message.structure.namespaced_type.name)
46 |
47 | def __init__(self) -> None: ...
48 |
--------------------------------------------------------------------------------
/rosidl_generator_mypy-extras.cmake.in:
--------------------------------------------------------------------------------
1 | include("${CMAKE_CURRENT_LIST_DIR}/register_mypy.cmake")
2 | rosidl_generator_mypy_extras(
3 | "${rosidl_generator_mypy_DIR}/../../../lib/rosidl_generator_mypy/rosidl_generator_mypy"
4 | "${rosidl_generator_mypy_DIR}/../../../@PYTHON_INSTALL_DIR@/rosidl_generator_mypy/__init__.py"
5 | "${rosidl_generator_mypy_DIR}/../resource"
6 | )
7 |
--------------------------------------------------------------------------------
/rosidl_generator_mypy/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pathlib
3 | from typing import Dict, List, NamedTuple, Optional, Set, Tuple
4 |
5 | from rosidl_cmake import (
6 | convert_camel_case_to_lower_case_underscore,
7 | generate_files,
8 | read_generator_arguments,
9 | )
10 | from rosidl_generator_py import generate_py_impl
11 | from rosidl_parser.definition import (
12 | AbstractNestedType,
13 | AbstractSequence,
14 | AbstractType,
15 | Action,
16 | Array,
17 | IdlContent,
18 | IdlLocator,
19 | Message,
20 | NamespacedType,
21 | Service,
22 | )
23 | from rosidl_parser.parser import parse_idl_file
24 |
25 | SPECIAL_NESTED_BASIC_TYPES = ["int", "float"]
26 |
27 |
28 | class Annotation(NamedTuple):
29 | getter: str
30 | setter: str
31 |
32 |
33 | def generate(generator_arguments_file: str) -> List[str]:
34 | mapping = {
35 | "_idl.pyi.em": "_%s.pyi",
36 | }
37 | generated_files: List[str] = generate_files(generator_arguments_file, mapping)
38 |
39 | args = read_generator_arguments(generator_arguments_file)
40 | package_name = args["package_name"]
41 |
42 | # For __init__.pyi, it is required to output the exact same contents as
43 | # rosidl_python does.
44 | modules: Dict[str, Set[str]] = {}
45 | idl_content = IdlContent()
46 | for idl_tuple in args.get("idl_tuples", []):
47 | idl_parts = idl_tuple.rsplit(":", 1)
48 | assert len(idl_parts) == 2
49 |
50 | idl_rel_path = pathlib.Path(idl_parts[1])
51 | idl_stems = modules.setdefault(str(idl_rel_path.parent), set())
52 | idl_stems.add(idl_rel_path.stem)
53 |
54 | locator = IdlLocator(*idl_parts)
55 | idl_file = parse_idl_file(locator)
56 | idl_content.elements += idl_file.content.elements
57 |
58 | for subfolder in modules.keys():
59 | with open(
60 | os.path.join(args["output_dir"], subfolder, "__init__.pyi"), "w"
61 | ) as f:
62 | for idl_stem in sorted(modules[subfolder]):
63 | module_name = "_{}".format(
64 | convert_camel_case_to_lower_case_underscore(idl_stem)
65 | )
66 | f.write(
67 | f"from {package_name}.{subfolder}.{module_name} import "
68 | f"{idl_stem} as {idl_stem} # noqa: F401\n"
69 | )
70 |
71 | return generated_files
72 |
73 |
74 | def get_defined_classes_msg(msg: Message) -> Set[str]:
75 | return {msg.structure.namespaced_type.name}
76 |
77 |
78 | def get_defined_classes_srv(srv: Service) -> Set[str]:
79 | ret: Set[str] = {srv.namespaced_type.name}
80 | ret.update(get_defined_classes_msg(srv.request_message))
81 | ret.update(get_defined_classes_msg(srv.response_message))
82 | return ret
83 |
84 |
85 | def get_defined_classes_action(action: Action) -> Set[str]:
86 | ret: Set[str] = {action.namespaced_type.name}
87 | ret.update(get_defined_classes_msg(action.goal))
88 | ret.update(get_defined_classes_msg(action.result))
89 | ret.update(get_defined_classes_msg(action.feedback))
90 | ret.update(get_defined_classes_srv(action.send_goal_service))
91 | ret.update(get_defined_classes_srv(action.get_result_service))
92 | ret.update(get_defined_classes_msg(action.feedback_message))
93 |
94 | return ret
95 |
96 |
97 | def get_defined_classes(content: IdlContent) -> Set[str]:
98 | ret: Set[str] = set()
99 | for item in content.elements:
100 | if isinstance(item, Message):
101 | ret.update(get_defined_classes_msg(item))
102 | elif isinstance(item, Service):
103 | ret.update(get_defined_classes_srv(item))
104 | elif isinstance(item, Action):
105 | ret.update(get_defined_classes_action(item))
106 |
107 | return ret
108 |
109 |
110 | def to_type_annotation(
111 | current_namespace: NamespacedType, defined_classes: Set[str], type_: AbstractType
112 | ) -> Annotation:
113 | if isinstance(type_, NamespacedType):
114 | if type_.namespaces == current_namespace.namespaces:
115 | if type_.name in defined_classes:
116 | # member is defined in the same module, so no need to add namespaces
117 | annotation = '"{}"'.format(type_.name)
118 | return Annotation(annotation, annotation)
119 |
120 | # NOTE: We export .pyi files, which don't affect the Python code execution at all.
121 | # As mypy solves the import cycles properly,
122 | # we import classes from not a module but a package.
123 | # (i.e. in the same way as imports for other packages)
124 |
125 | annotation = "{}.{}".format(".".join(type_.namespaces), type_.name)
126 | return Annotation(annotation, annotation)
127 |
128 | try:
129 | ret = generate_py_impl.get_python_type(type_)
130 | if ret is not None:
131 | return Annotation(str(ret), str(ret))
132 | except Exception:
133 | pass
134 |
135 | if isinstance(type_, Array):
136 | # The type_ will be Array for bounded lists
137 | type_annotation = to_type_annotation(
138 | current_namespace, defined_classes, type_.value_type
139 | )
140 | if type_annotation.getter in SPECIAL_NESTED_BASIC_TYPES:
141 | # eg: int64[4]
142 | return Annotation(
143 | "np.ndarray",
144 | "typing.Union[typing.Sequence[{}], np.ndarray]".format(
145 | type_annotation.setter
146 | ),
147 | )
148 |
149 | # eg: std_msgs/Header[4]
150 | return Annotation(
151 | "typing.Sequence[{}]".format(type_annotation.getter),
152 | "typing.Sequence[{}]".format(type_annotation.setter),
153 | )
154 | if isinstance(type_, AbstractSequence):
155 | # The type_ will be AbstractSequence for unbounded lists
156 | type_annotation = to_type_annotation(
157 | current_namespace, defined_classes, type_.value_type
158 | )
159 | if type_annotation.getter in SPECIAL_NESTED_BASIC_TYPES:
160 | # eg: int64[]
161 | return Annotation(
162 | "array.array[{}]".format(type_annotation.getter),
163 | "typing.Sequence[{}]".format(type_annotation.setter),
164 | )
165 |
166 | # eg: std_msgs/Header[]
167 | return Annotation(
168 | "typing.MutableSequence[{}]".format(type_annotation.getter),
169 | "typing.Sequence[{}]".format(type_annotation.setter),
170 | )
171 |
172 | return Annotation(str(type_), str(type_))
173 |
174 |
175 | def _get_import_statement(
176 | current_namespace: NamespacedType, defined_classes: Set[str], type_: AbstractType
177 | ) -> Tuple[Optional[str], bool]:
178 | if isinstance(type_, NamespacedType):
179 | is_firstparty = False
180 | if type_.namespaces == current_namespace.namespaces:
181 | is_firstparty = True
182 |
183 | if type_.name in defined_classes:
184 | # member is defined in the same module, so no need to add imports
185 | return None, is_firstparty
186 |
187 | return "import {}".format(".".join(type_.namespaces)), is_firstparty
188 |
189 | if isinstance(type_, AbstractNestedType):
190 | return _get_import_statement(
191 | current_namespace, defined_classes, type_.value_type
192 | )
193 |
194 | return None, False
195 |
196 |
197 | def append_import_statements_msg(
198 | msg: Message,
199 | defined_classes: Set[str],
200 | third_parties: Set[str],
201 | first_parties: Set[str],
202 | ) -> None:
203 | third_parties.add("import rosidl_parser.definition")
204 | if msg.structure is None or msg.structure.members is None:
205 | return None
206 |
207 | for member in msg.structure.members:
208 | ret, is_first_party = _get_import_statement(
209 | msg.structure.namespaced_type, defined_classes, member.type
210 | )
211 | if ret is not None:
212 | if is_first_party:
213 | first_parties.add(ret)
214 | else:
215 | third_parties.add(ret)
216 |
217 |
218 | def append_import_statements_srv(
219 | srv: Service,
220 | defined_classes: Set[str],
221 | third_parties: Set[str],
222 | first_parties: Set[str],
223 | ) -> None:
224 | append_import_statements_msg(
225 | srv.request_message, defined_classes, third_parties, first_parties
226 | )
227 | append_import_statements_msg(
228 | srv.response_message, defined_classes, third_parties, first_parties
229 | )
230 |
231 |
232 | def append_import_statements_action(
233 | action: Action,
234 | defined_classes: Set[str],
235 | third_parties: Set[str],
236 | first_parties: Set[str],
237 | ) -> None:
238 | append_import_statements_msg(
239 | action.goal, defined_classes, third_parties, first_parties
240 | )
241 | append_import_statements_msg(
242 | action.result, defined_classes, third_parties, first_parties
243 | )
244 | append_import_statements_msg(
245 | action.feedback, defined_classes, third_parties, first_parties
246 | )
247 | append_import_statements_srv(
248 | action.send_goal_service, defined_classes, third_parties, first_parties
249 | )
250 | append_import_statements_srv(
251 | action.get_result_service, defined_classes, third_parties, first_parties
252 | )
253 | append_import_statements_msg(
254 | action.feedback_message, defined_classes, third_parties, first_parties
255 | )
256 |
--------------------------------------------------------------------------------
/rosidl_generator_mypy/cli.py:
--------------------------------------------------------------------------------
1 | import pathlib
2 | from typing import List
3 |
4 | from ament_index_python import get_package_share_directory
5 | from rosidl_cli.command.generate.extensions import GenerateCommandExtension
6 | from rosidl_cli.command.helpers import legacy_generator_arguments_file
7 | from rosidl_cli.command.translate.api import translate
8 |
9 | from rosidl_generator_mypy import generate
10 |
11 |
12 | class GenerateMypy(GenerateCommandExtension): # type: ignore
13 | def generate(
14 | self,
15 | package_name: str,
16 | interface_files: List[str],
17 | include_paths: List[pathlib.Path],
18 | output_path: pathlib.Path,
19 | ) -> List[str]:
20 | generated_files: List[str] = []
21 |
22 | package_share_path = pathlib.Path(
23 | get_package_share_directory("rosidl_generator_mypy")
24 | )
25 | templates_path = package_share_path / "resource"
26 |
27 | # Normalize interface definition format to .idl
28 | idl_interface_files: List[str] = []
29 | non_idl_interface_files: List[str] = []
30 | for path in interface_files:
31 | if not path.endswith(".idl"):
32 | non_idl_interface_files.append(path)
33 | else:
34 | idl_interface_files.append(path)
35 | if non_idl_interface_files:
36 | idl_interface_files.extend(
37 | translate(
38 | package_name=package_name,
39 | interface_files=non_idl_interface_files,
40 | include_paths=include_paths,
41 | output_format="idl",
42 | output_path=output_path / "tmp",
43 | )
44 | )
45 |
46 | # Generate code
47 | with legacy_generator_arguments_file(
48 | package_name=package_name,
49 | interface_files=idl_interface_files,
50 | include_paths=include_paths,
51 | templates_path=templates_path,
52 | output_path=output_path,
53 | ) as path_to_arguments_file:
54 | generated_files.extend(generate(path_to_arguments_file))
55 |
56 | return generated_files
57 |
--------------------------------------------------------------------------------
/rosidl_generator_mypy/py.typed:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rospypi/rosidl_generator_mypy/faa14634fb500b4661cb406869ced04e104c2e45/rosidl_generator_mypy/py.typed
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [options.entry_points]
2 | rosidl_cli.command.generate.type_extensions =
3 | mypy = rosidl_generator_mypy.cli:GenerateMypy
4 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import find_packages, setup
2 |
3 | setup(
4 | name="rosidl_generator_mypy",
5 | version="0.1.0",
6 | packages=find_packages(exclude=["tests"]),
7 | description="Generate stub files for the ROS2 interfaces in Python",
8 | long_description=open("README.rst").read(),
9 | author="Yuki Igarashi, Tamamki Nishino",
10 | author_email="me@bonprosoft.com, otamachan@gmail.com",
11 | classifiers=[
12 | "License :: OSI Approved :: Apache Software License",
13 | "Operating System :: MacOS",
14 | "Operating System :: Microsoft :: Windows",
15 | "Operating System :: POSIX",
16 | "Operating System :: Unix",
17 | "Programming Language :: Python :: 3.6",
18 | "Programming Language :: Python :: 3.7",
19 | "Programming Language :: Python :: 3.8",
20 | "Programming Language :: Python :: 3.9",
21 | "Programming Language :: Python :: 3.10",
22 | "Programming Language :: Python",
23 | ],
24 | license="Apache License 2.0",
25 | url="https://github.com/rospypi/rosidl_generator_mypy",
26 | include_package_data=True,
27 | zip_safe=False,
28 | )
29 |
--------------------------------------------------------------------------------