Skip to content

Commit

Permalink
Add valid package name check
Browse files Browse the repository at this point in the history
  • Loading branch information
rob-clarke committed Mar 19, 2021
1 parent d45cd35 commit 3860070
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
6 changes: 6 additions & 0 deletions ament_index_python/ament_index_python/packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import os
import re

from .resources import get_resource
from .resources import get_resources
Expand Down Expand Up @@ -44,7 +45,11 @@ def get_package_prefix(package_name):
:param str package_name: name of the package to locate
:returns: installation prefix of the package
:raises: :exc:`PackageNotFoundError` if the package is not found
:raises: :exc:`ValueError` if the package name is invalid
"""
if re.fullmatch('[a-z][a-z0-9_]+', package_name, re.ASCII) is None:
raise ValueError(
"'{}' is not a valid package name".format(package_name))
try:
content, package_prefix = get_resource('packages', package_name)
except LookupError:
Expand All @@ -65,5 +70,6 @@ def get_package_share_directory(package_name):
:param str package_name: name of the package to locate
:returns: share directory of the package
:raises: :exc:`PackageNotFoundError` if the package is not found
:raises: :exc:`ValueError` if the package name is invalid
"""
return os.path.join(get_package_prefix(package_name), 'share', package_name)
11 changes: 9 additions & 2 deletions ament_index_python/test/test_ament_index_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,15 @@ def get_package_prefix_basename(package_name):
get_package_prefix('does_not_exist')
assert issubclass(PackageNotFoundError, KeyError)

with pytest.raises(InvalidResourceNameError):
invalid_package_names = ['_package','packageA','package a','package/a','0package','package.a']
for name in invalid_package_names:
with pytest.raises(ValueError):
get_package_prefix(name)

with pytest.raises(ValueError):
# An absolue path is not a valid package name
extant_absolute_path = os.path.abspath(__file__)
get_package_prefix(extant_absolute_path)
assert issubclass(InvalidResourceNameError, ValueError)


def test_get_package_share_directory():
Expand All @@ -184,6 +188,9 @@ def get_package_share_directory_test(package_name, expect_prefix):
with pytest.raises(PackageNotFoundError):
get_package_share_directory('does_not_exist')

with pytest.raises(ValueError):
get_package_share_directory('/invalid/package/name')


def test_get_resource_types():
set_ament_prefix_path([])
Expand Down

0 comments on commit 3860070

Please sign in to comment.