Skip to content

Commit

Permalink
Validate whether the module name is installed in the current environment
Browse files Browse the repository at this point in the history
Closes #959
  • Loading branch information
Gordon Shotwell committed Jan 3, 2024
1 parent 10b896b commit cdf204a
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions shiny/_custom_component_template_questions.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,27 @@
import re
from importlib import util
from pathlib import Path

from prompt_toolkit.document import Document
from questionary import ValidationError, Validator


def is_existing_module(name: str) -> bool:
"""
Check if a module name can be imported, which indicates that it is either
a standard module name, or the name of an installed module.
In either case the new module would probably cause a name conflict.
"""
try:
spec = util.find_spec(name)
if spec is not None:
return True
else:
return False
except ImportError:
return False


def is_pep508_identifier(name: str):
"""
Checks if a package name is a PEP 508 identifier.
Expand Down Expand Up @@ -65,6 +82,14 @@ def validate(self, document: Document):
cursor_position=len(name),
)

# Using the name of an existing package causes an import error

if is_existing_module(name):
raise ValidationError(
message="Package already installed in your current environment.",
cursor_position=len(name),
)


def update_component_name_in_template(template_dir: Path, new_component_name: str):
"""
Expand Down

0 comments on commit cdf204a

Please sign in to comment.