util.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. """Utility."""
  2. from __future__ import annotations
  3. from functools import wraps, lru_cache
  4. import warnings
  5. import re
  6. from typing import Callable, Any
  7. DEBUG = 0x00001
  8. RE_PATTERN_LINE_SPLIT = re.compile(r'(?:\r\n|(?!\r\n)[\n\r])|$')
  9. UC_A = ord('A')
  10. UC_Z = ord('Z')
  11. @lru_cache(maxsize=512)
  12. def lower(string: str) -> str:
  13. """Lower."""
  14. new_string = []
  15. for c in string:
  16. o = ord(c)
  17. new_string.append(chr(o + 32) if UC_A <= o <= UC_Z else c)
  18. return ''.join(new_string)
  19. class SelectorSyntaxError(Exception):
  20. """Syntax error in a CSS selector."""
  21. def __init__(self, msg: str, pattern: str | None = None, index: int | None = None) -> None:
  22. """Initialize."""
  23. self.line = None
  24. self.col = None
  25. self.context = None
  26. if pattern is not None and index is not None:
  27. # Format pattern to show line and column position
  28. self.context, self.line, self.col = get_pattern_context(pattern, index)
  29. msg = f'{msg}\n line {self.line}:\n{self.context}'
  30. super().__init__(msg)
  31. def deprecated(message: str, stacklevel: int = 2) -> Callable[..., Any]: # pragma: no cover
  32. """
  33. Raise a `DeprecationWarning` when wrapped function/method is called.
  34. Usage:
  35. @deprecated("This method will be removed in version X; use Y instead.")
  36. def some_method()"
  37. pass
  38. """
  39. def _wrapper(func: Callable[..., Any]) -> Callable[..., Any]:
  40. @wraps(func)
  41. def _deprecated_func(*args: Any, **kwargs: Any) -> Any:
  42. warnings.warn(
  43. f"'{func.__name__}' is deprecated. {message}",
  44. category=DeprecationWarning,
  45. stacklevel=stacklevel
  46. )
  47. return func(*args, **kwargs)
  48. return _deprecated_func
  49. return _wrapper
  50. def warn_deprecated(message: str, stacklevel: int = 2) -> None: # pragma: no cover
  51. """Warn deprecated."""
  52. warnings.warn(
  53. message,
  54. category=DeprecationWarning,
  55. stacklevel=stacklevel
  56. )
  57. def get_pattern_context(pattern: str, index: int) -> tuple[str, int, int]:
  58. """Get the pattern context."""
  59. last = 0
  60. current_line = 1
  61. col = 1
  62. text = [] # type: list[str]
  63. line = 1
  64. offset = None # type: int | None
  65. # Split pattern by newline and handle the text before the newline
  66. for m in RE_PATTERN_LINE_SPLIT.finditer(pattern):
  67. linetext = pattern[last:m.start(0)]
  68. if not len(m.group(0)) and not len(text):
  69. indent = ''
  70. offset = -1
  71. col = index - last + 1
  72. elif last <= index < m.end(0):
  73. indent = '--> '
  74. offset = (-1 if index > m.start(0) else 0) + 3
  75. col = index - last + 1
  76. else:
  77. indent = ' '
  78. offset = None
  79. if len(text):
  80. # Regardless of whether we are presented with `\r\n`, `\r`, or `\n`,
  81. # we will render the output with just `\n`. We will still log the column
  82. # correctly though.
  83. text.append('\n')
  84. text.append(f'{indent}{linetext}')
  85. if offset is not None:
  86. text.append('\n')
  87. text.append(' ' * (col + offset) + '^')
  88. line = current_line
  89. current_line += 1
  90. last = m.end(0)
  91. return ''.join(text), line, col