Skip to content

Commit

Permalink
Add types rosidl_pycommon (#824)
Browse files Browse the repository at this point in the history
* add types

Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>

* use hasattr check

Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>

* flake8

Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>

* use str instead

Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>

---------

Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
  • Loading branch information
InvincibleRMC authored Sep 13, 2024
1 parent e25750d commit c027a38
Show file tree
Hide file tree
Showing 12 changed files with 68 additions and 27 deletions.
6 changes: 4 additions & 2 deletions rosidl_generator_c/rosidl_generator_c/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import List

from rosidl_generator_type_description import parse_rihs_string
from rosidl_generator_type_description import RIHS01_HASH_VALUE_SIZE
from rosidl_parser.definition import AbstractGenericString
Expand All @@ -28,7 +30,7 @@
from rosidl_pycommon import generate_files


def generate_c(generator_arguments_file, disable_description_codegen=False):
def generate_c(generator_arguments_file, disable_description_codegen: bool = False) -> List[str]:
mapping = {
'idl.h.em': '%s.h',
'idl__description.c.em': 'detail/%s__description.c',
Expand All @@ -46,7 +48,7 @@ def generate_c(generator_arguments_file, disable_description_codegen=False):
})


def prefix_with_bom_if_necessary(content):
def prefix_with_bom_if_necessary(content: str) -> str:
try:
content.encode('ASCII')
except UnicodeError:
Expand Down
5 changes: 3 additions & 2 deletions rosidl_generator_cpp/rosidl_generator_cpp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

from ast import literal_eval
from typing import List

from rosidl_parser.definition import AbstractGenericString
from rosidl_parser.definition import AbstractNestedType
Expand All @@ -28,7 +29,7 @@
from rosidl_pycommon import generate_files


def generate_cpp(generator_arguments_file):
def generate_cpp(generator_arguments_file) -> List[str]:
mapping = {
'idl.hpp.em': '%s.hpp',
'idl__builder.hpp.em': 'detail/%s__builder.hpp',
Expand All @@ -41,7 +42,7 @@ def generate_cpp(generator_arguments_file):
post_process_callback=prefix_with_bom_if_necessary)


def prefix_with_bom_if_necessary(content):
def prefix_with_bom_if_necessary(content: str) -> str:
try:
content.encode('ASCII')
except UnicodeError:
Expand Down
1 change: 1 addition & 0 deletions rosidl_pycommon/package.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<test_depend>ament_copyright</test_depend>
<test_depend>ament_flake8</test_depend>
<test_depend>ament_pep257</test_depend>
<test_depend>ament_mypy</test_depend>
<test_depend>python3-pytest</test_depend>

<export>
Expand Down
Empty file added rosidl_pycommon/py.typed
Empty file.
43 changes: 26 additions & 17 deletions rosidl_pycommon/rosidl_pycommon/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import pathlib
import re
import sys
from typing import Any, Callable, Dict, List, Optional

import em

Expand All @@ -31,7 +32,7 @@
from rosidl_parser.parser import parse_idl_file


def convert_camel_case_to_lower_case_underscore(value):
def convert_camel_case_to_lower_case_underscore(value: str) -> str:
# insert an underscore before any upper case letter
# which is followed by a lower case letter
value = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', value)
Expand All @@ -41,12 +42,14 @@ def convert_camel_case_to_lower_case_underscore(value):
return value.lower()


def read_generator_arguments(input_file):
def read_generator_arguments(input_file: str) -> Any:
with open(input_file, mode='r', encoding='utf-8') as h:
return json.load(h)


def get_newest_modification_time(target_dependencies):
def get_newest_modification_time(
target_dependencies: List[str]
) -> Optional[float]:
newest_timestamp = None
for dep in target_dependencies:
ts = os.path.getmtime(dep)
Expand All @@ -56,9 +59,10 @@ def get_newest_modification_time(target_dependencies):


def generate_files(
generator_arguments_file, mapping, additional_context=None,
keep_case=False, post_process_callback=None
):
generator_arguments_file: str, mapping: Dict[str, str],
additional_context: Optional[Dict[str, bool]] = None,
keep_case: bool = False, post_process_callback: Optional[Callable[[str], str]] = None
) -> List[str]:
args = read_generator_arguments(generator_arguments_file)

template_basepath = pathlib.Path(args['template_dir'])
Expand All @@ -67,7 +71,7 @@ def generate_files(
'Could not find template: ' + template_filename

latest_target_timestamp = get_newest_modification_time(args['target_dependencies'])
generated_files = []
generated_files: List[str] = []

type_description_files = {}
for description_tuple in args.get('type_description_tuples', []):
Expand Down Expand Up @@ -128,10 +132,10 @@ def generate_files(
return generated_files


template_prefix_path = []
template_prefix_path: List[pathlib.Path] = []


def get_template_path(template_name):
def get_template_path(template_name: str) -> pathlib.Path:
global template_prefix_path
for basepath in template_prefix_path:
template_path = basepath / template_name
Expand All @@ -144,14 +148,16 @@ def get_template_path(template_name):


def expand_template(
template_name, data, output_file, minimum_timestamp=None,
template_basepath=None, post_process_callback=None
):
template_name: str, data: Dict[str, Any], output_file: str,
minimum_timestamp: Optional[float] = None,
template_basepath: Optional[pathlib.Path] = None,
post_process_callback: Optional[Callable[[str], str]] = None
) -> None:
# in the legacy API the first argument was the path to the template
if template_basepath is None:
template_name = pathlib.Path(template_name)
template_basepath = template_name.parent
template_name = template_name.name
template_path = pathlib.Path(template_name)
template_basepath = template_path.parent
template_name = template_path.name

global template_prefix_path
template_prefix_path.append(template_basepath)
Expand Down Expand Up @@ -226,14 +232,17 @@ def expand_template(
h.write(content)


def _add_helper_functions(data):
def _add_helper_functions(data: Dict[str, Any]) -> None:
data['TEMPLATE'] = _expand_template


def _expand_template(template_name, **kwargs):
def _expand_template(template_name: str, **kwargs: Any) -> None:
global interpreter
template_path = get_template_path(template_name)
_add_helper_functions(kwargs)
if interpreter is None:
raise RuntimeError('_expand_template called before expand_template')

with template_path.open('r') as h:
interpreter.invoke(
'beforeInclude', name=str(template_path), file=h, locals=kwargs)
Expand Down
2 changes: 1 addition & 1 deletion rosidl_pycommon/test/test_copyright.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@

@pytest.mark.copyright
@pytest.mark.linter
def test_copyright():
def test_copyright() -> None:
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found errors'
2 changes: 1 addition & 1 deletion rosidl_pycommon/test/test_flake8.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

@pytest.mark.flake8
@pytest.mark.linter
def test_flake8():
def test_flake8() -> None:
rc, errors = main_with_errors(argv=[])
assert rc == 0, \
'Found %d code style errors / warnings:\n' % len(errors) + \
Expand Down
23 changes: 23 additions & 0 deletions rosidl_pycommon/test/test_mypy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Copyright 2024 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 ament_mypy.main import main
import pytest


@pytest.mark.mypy
@pytest.mark.linter
def test_mypy() -> None:
rc = main(argv=[])
assert rc == 0, 'Found type errors!'
2 changes: 1 addition & 1 deletion rosidl_pycommon/test/test_pep257.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@

@pytest.mark.linter
@pytest.mark.pep257
def test_pep257():
def test_pep257() -> None:
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found code style errors / warnings'
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import List

from rosidl_pycommon import generate_files


def generate_c(generator_arguments_file: str):
def generate_c(generator_arguments_file: str) -> List[str]:
"""
Generate the C implementation of the type support.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import List

from rosidl_pycommon import generate_files


def generate_cpp(generator_arguments_file: str):
def generate_cpp(generator_arguments_file: str) -> List[str]:
"""
Generate the C++ implementation of the type support.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import pathlib
from typing import List

from ament_index_python import get_package_share_directory

Expand All @@ -32,7 +33,7 @@ def generate(
interface_files,
include_paths,
output_path
):
) -> List[str]:
package_share_path = pathlib.Path(
get_package_share_directory('rosidl_typesupport_introspection_cpp'))

Expand Down

0 comments on commit c027a38

Please sign in to comment.