🐛 fix(directory_reader.py): handle SyntaxError when parsing code to prevent crashes
🐛 fix(directory_reader.py): return False if code is not valid Python to prevent false positives 🐛 fix(directory_reader.py): fix method name from is_type_hint_used_but_not_imported to _is_type_hint_used_in_args for consistency 🐛 fix(directory_reader.py): fix method name from is_type_hint_imported to _is_type_hint_imported for consistency 🐛 fix(directory_reader.py): fix return value of _is_type_hint_used_in_args method to return False if type hint is used but not imported
This commit is contained in:
parent
261e258ed4
commit
564634d36c
1 changed files with 19 additions and 10 deletions
|
|
@ -152,15 +152,19 @@ class DirectoryReader:
|
||||||
Check if a specific type hint is used in the
|
Check if a specific type hint is used in the
|
||||||
function definitions within the given code.
|
function definitions within the given code.
|
||||||
"""
|
"""
|
||||||
module = ast.parse(code)
|
try:
|
||||||
|
module = ast.parse(code)
|
||||||
|
|
||||||
for node in ast.walk(module):
|
for node in ast.walk(module):
|
||||||
if isinstance(node, ast.FunctionDef):
|
if isinstance(node, ast.FunctionDef):
|
||||||
for arg in node.args.args:
|
for arg in node.args.args:
|
||||||
if self._is_type_hint_in_arg_annotation(
|
if self._is_type_hint_in_arg_annotation(
|
||||||
arg.annotation, type_hint_name
|
arg.annotation, type_hint_name
|
||||||
):
|
):
|
||||||
return True
|
return True
|
||||||
|
except SyntaxError:
|
||||||
|
# Returns False if the code is not valid Python
|
||||||
|
return False
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _is_type_hint_in_arg_annotation(self, annotation, type_hint_name: str) -> bool:
|
def _is_type_hint_in_arg_annotation(self, annotation, type_hint_name: str) -> bool:
|
||||||
|
|
@ -204,8 +208,13 @@ class DirectoryReader:
|
||||||
return False, "Syntax error"
|
return False, "Syntax error"
|
||||||
elif not self.validate_build(file_content):
|
elif not self.validate_build(file_content):
|
||||||
return False, "Missing build function"
|
return False, "Missing build function"
|
||||||
elif self.is_type_hint_used_but_not_imported("Optional", file_content):
|
elif self._is_type_hint_used_in_args(
|
||||||
return False, "Type hint 'Optional' is used but not imported in the code."
|
"Optional", file_content
|
||||||
|
) and not self._is_type_hint_imported("Optional", file_content):
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
"Type hint 'Optional' is used but not imported in the code.",
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
if self.compress_code_field:
|
if self.compress_code_field:
|
||||||
file_content = str(StringCompressor(file_content).compress_string())
|
file_content = str(StringCompressor(file_content).compress_string())
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue