diff --git a/sentry_sdk/utils.py b/sentry_sdk/utils.py index 49b4a0c76c..fe3302700b 100644 --- a/sentry_sdk/utils.py +++ b/sentry_sdk/utils.py @@ -195,6 +195,13 @@ def __init__(self, value, metadata): self.metadata = metadata +if MYPY: + from typing import TypeVar + + T = TypeVar("T") + Annotated = Union[AnnotatedValue, T] + + def get_type_name(cls): # type: (Optional[type]) -> Optional[str] return getattr(cls, "__qualname__", None) or getattr(cls, "__name__", None) @@ -236,22 +243,13 @@ def iter_stacks(tb): tb_ = tb_.tb_next -def slim_string(value, length=MAX_STRING_LENGTH): - # type: (str, int) -> str - if not value: - return value - if len(value) > length: - return value[: length - 3] + "..." - return value[:length] - - def get_lines_from_file( filename, # type: str lineno, # type: int loader=None, # type: Optional[Any] module=None, # type: Optional[str] ): - # type: (...) -> Tuple[List[str], Optional[str], List[str]] + # type: (...) -> Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]] context_lines = 5 source = None if loader is not None and hasattr(loader, "get_source"): @@ -276,11 +274,11 @@ def get_lines_from_file( try: pre_context = [ - slim_string(line.strip("\r\n")) for line in source[lower_bound:lineno] + strip_string(line.strip("\r\n")) for line in source[lower_bound:lineno] ] - context_line = slim_string(source[lineno].strip("\r\n")) + context_line = strip_string(source[lineno].strip("\r\n")) post_context = [ - slim_string(line.strip("\r\n")) + strip_string(line.strip("\r\n")) for line in source[(lineno + 1) : upper_bound] ] return pre_context, context_line, post_context @@ -289,8 +287,11 @@ def get_lines_from_file( return [], None, [] -def get_source_context(frame, tb_lineno): - # type: (FrameType, int) -> Tuple[List[str], Optional[str], List[str]] +def get_source_context( + frame, # type: FrameType + tb_lineno, # type: int +): + # type: (...) -> Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]] try: abs_path = frame.f_code.co_filename # type: Optional[str] except Exception: @@ -652,12 +653,18 @@ def _module_in_set(name, set): return False -def strip_string(value, max_length=512): - # type: (str, int) -> Union[AnnotatedValue, str] +def strip_string(value, max_length=None): + # type: (str, Optional[int]) -> Union[AnnotatedValue, str] # TODO: read max_length from config if not value: return value + + if max_length is None: + # This is intentionally not just the default such that one can patch `MAX_STRING_LENGTH` and affect `strip_string`. + max_length = MAX_STRING_LENGTH + length = len(value) + if length > max_length: return AnnotatedValue( value=value[: max_length - 3] + u"...",