Skip to content

Commit

Permalink
Attempt to fix mypy errors
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzodb1 committed May 2, 2024
1 parent e370f63 commit 6f3da86
Show file tree
Hide file tree
Showing 11 changed files with 32 additions and 19 deletions.
3 changes: 2 additions & 1 deletion detect_secrets/audit/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple

from ..constants import VerifiedResult
Expand All @@ -26,7 +27,7 @@ def from_class(secret_class: VerifiedResult) -> 'SecretClassToPrint':

def generate_report(
baseline_file: str,
class_to_print: SecretClassToPrint = None,
class_to_print: Optional[SecretClassToPrint] = None,
line_getter_factory: Callable[[str], 'LineGetter'] = open_file,
) -> Dict[str, List[Dict[str, Any]]]:

Expand Down
15 changes: 9 additions & 6 deletions detect_secrets/core/plugins/initialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,37 @@
from typing import List
from typing import Type

from ...plugins.base import BasePlugin
from ...settings import get_settings
from ..log import log
from .util import get_mapping_from_secret_type_to_class
from .util import get_plugins_from_file
from .util import Plugin


def from_secret_type(secret_type: str) -> Plugin:
def from_secret_type(secret_type: str) -> BasePlugin:
"""
:raises: TypeError
"""
try:
plugin_type = get_mapping_from_secret_type_to_class()[secret_type]
plugin_type: Dict[str, Type[Plugin]] = get_mapping_from_secret_type_to_class()[secret_type]
except KeyError:
raise TypeError

try:
return plugin_type(**_get_config(plugin_type.__name__))
plugin: Plugin = plugin_type(**_get_config(plugin_type.__name__))
return plugin
except TypeError:
log.error('Unable to initialize plugin!')
raise


def from_plugin_classname(classname: str) -> Plugin:
def from_plugin_classname(classname: str) -> BasePlugin:
"""
:raises: TypeError
"""
try:
plugin_types = get_mapping_from_secret_type_to_class().values()
plugin_types: Iterable[Type[Plugin]] = get_mapping_from_secret_type_to_class().values()
except FileNotFoundError as e:
log.error(f'Error: Failed to load `{classname}` plugin: {e}')
log.error(
Expand All @@ -54,7 +56,8 @@ def from_plugin_classname(classname: str) -> Plugin:
raise TypeError

try:
return plugin_type(**_get_config(classname))
plugin: Plugin = plugin_type(**_get_config(classname))
return plugin
except TypeError:
log.error('Unable to initialize plugin!')
raise
Expand Down
2 changes: 1 addition & 1 deletion detect_secrets/core/secrets_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class PatchedFile:
"""This exists so that we can do typecasting, without importing unidiff."""
path: str

def __iter__(self) -> Generator:
def __iter__(self) -> Generator: # type: ignore
pass


Expand Down
3 changes: 2 additions & 1 deletion detect_secrets/core/usage/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
from typing import cast
from typing import Iterable
from typing import Set

from .. import plugins
from ...exceptions import InvalidFile
Expand Down Expand Up @@ -87,7 +88,7 @@ def minmax_type(string: str) -> float:

def _add_disable_flag(parser: argparse._ArgumentGroup) -> None:
def valid_plugin_name(string: str) -> str:
valid_plugin_names = {
valid_plugin_names: Set[str] = {
item.__name__
for item in get_mapping_from_secret_type_to_class().values()
}
Expand Down
5 changes: 3 additions & 2 deletions detect_secrets/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from .exceptions import InvalidBaselineError
from .settings import get_plugins
from .settings import get_settings
from detect_secrets.audit.report import SecretClassToPrint


def main(argv: Optional[List[str]] = None) -> int:
Expand Down Expand Up @@ -132,9 +133,9 @@ def handle_audit_action(args: argparse.Namespace) -> None:
elif args.report:
class_to_print = None
if args.only_real:
class_to_print = audit.report.SecretClassToPrint.REAL_SECRET
class_to_print: SecretClassToPrint = SecretClassToPrint.REAL_SECRET
elif args.only_false:
class_to_print = audit.report.SecretClassToPrint.FALSE_POSITIVE
class_to_print: SecretClassToPrint = SecretClassToPrint.FALSE_POSITIVE
print(
json.dumps(
audit.report.generate_report(args.filename[0], class_to_print),
Expand Down
3 changes: 2 additions & 1 deletion detect_secrets/plugins/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from typing import Dict
from typing import Generator
from typing import Iterable
from typing import Optional
from typing import Pattern
from typing import Set

Expand Down Expand Up @@ -48,7 +49,7 @@ def analyze_line(
filename: str,
line: str,
line_number: int = 0,
context: CodeSnippet = None,
context: Optional[CodeSnippet] = None,
**kwargs: Any
) -> Set[PotentialSecret]:
"""This examines a line and finds all possible secret values in it."""
Expand Down
3 changes: 2 additions & 1 deletion detect_secrets/plugins/high_entropy_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import cast
from typing import Dict
from typing import Generator
from typing import Optional
from typing import Set

from ..core.potential_secret import PotentialSecret
Expand Down Expand Up @@ -46,7 +47,7 @@ def analyze_line(
filename: str,
line: str,
line_number: int = 0,
context: CodeSnippet = None,
context: Optional[CodeSnippet] = None,
enable_eager_search: bool = False,
**kwargs: Any,
) -> Set[PotentialSecret]:
Expand Down
2 changes: 1 addition & 1 deletion detect_secrets/plugins/keyword.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def analyze_line(
filename: str,
line: str,
line_number: int = 0,
context: CodeSnippet = None,
context: Optional[CodeSnippet] = None,
**kwargs: Any,
) -> Set[PotentialSecret]:
filetype = determine_file_type(filename)
Expand Down
6 changes: 5 additions & 1 deletion detect_secrets/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@
from typing import Any
from typing import Dict
from typing import Generator
from typing import Iterable
from typing import List
from typing import Type
from urllib.parse import urlparse

from .exceptions import InvalidFile
from .util.importlib import import_file_as_module
from detect_secrets.core.plugins.util import Plugin


@lru_cache(maxsize=1)
Expand Down Expand Up @@ -65,10 +68,11 @@ def default_settings() -> Generator['Settings', None, None]:
"""Convenience function to enable all plugins and default filters."""
from .core.plugins.util import get_mapping_from_secret_type_to_class

plugin_types: Iterable[Type[Plugin]] = get_mapping_from_secret_type_to_class().values()
with transient_settings({
'plugins_used': [
{'name': plugin_type.__name__}
for plugin_type in get_mapping_from_secret_type_to_class().values()
for plugin_type in plugin_types
],
}) as settings:
yield settings
Expand Down
6 changes: 4 additions & 2 deletions detect_secrets/transformers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,17 @@ def get_transformed_file(
file: NamedIO,
use_eager_transformers: bool = False,
) -> Optional[List[str]]:
for transformer in get_transformers():
tranformers: Iterable[Transformer] = get_transformers()
for transformer in tranformers:
if not transformer.should_parse_file(file.name):
continue

if use_eager_transformers != transformer.is_eager:
continue

try:
return transformer.parse_file(file)
parsed_file: Optional[List[str]] = transformer.parse_file(file)
return parsed_file
except ParsingError:
pass
finally:
Expand Down
3 changes: 1 addition & 2 deletions detect_secrets/types.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from io import TextIOBase
from typing import Any
from typing import NamedTuple
from typing import NoReturn
from typing import Optional
from typing import Set

Expand All @@ -20,7 +19,7 @@ class SelfAwareCallable:
# The variable names for its inputs
injectable_variables: Set[str]

def __call__(self, *args: Any, **kwargs: Any) -> NoReturn:
def __call__(self, *args: Any, **kwargs: Any):
"""
This is needed, since you can't inherit Callable.
Source: https://stackoverflow.com/a/52654516/13340678
Expand Down

0 comments on commit 6f3da86

Please sign in to comment.