message_id_store.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  3. from typing import Dict, List, NoReturn, Optional, Tuple
  4. from pylint.exceptions import InvalidMessageError, UnknownMessageError
  5. class MessageIdStore:
  6. """The MessageIdStore store MessageId and make sure that there is a 1-1 relation between msgid and symbol."""
  7. def __init__(self) -> None:
  8. self.__msgid_to_symbol: Dict[str, str] = {}
  9. self.__symbol_to_msgid: Dict[str, str] = {}
  10. self.__old_names: Dict[str, List[str]] = {}
  11. def __len__(self) -> int:
  12. return len(self.__msgid_to_symbol)
  13. def __repr__(self) -> str:
  14. result = "MessageIdStore: [\n"
  15. for msgid, symbol in self.__msgid_to_symbol.items():
  16. result += f" - {msgid} ({symbol})\n"
  17. result += "]"
  18. return result
  19. def get_symbol(self, msgid: str) -> str:
  20. try:
  21. return self.__msgid_to_symbol[msgid.upper()]
  22. except KeyError as e:
  23. msg = f"'{msgid}' is not stored in the message store."
  24. raise UnknownMessageError(msg) from e
  25. def get_msgid(self, symbol: str) -> str:
  26. try:
  27. return self.__symbol_to_msgid[symbol]
  28. except KeyError as e:
  29. msg = f"'{symbol}' is not stored in the message store."
  30. raise UnknownMessageError(msg) from e
  31. def register_message_definition(
  32. self, msgid: str, symbol: str, old_names: List[Tuple[str, str]]
  33. ) -> None:
  34. self.check_msgid_and_symbol(msgid, symbol)
  35. self.add_msgid_and_symbol(msgid, symbol)
  36. for old_msgid, old_symbol in old_names:
  37. self.check_msgid_and_symbol(old_msgid, old_symbol)
  38. self.add_legacy_msgid_and_symbol(old_msgid, old_symbol, msgid)
  39. def add_msgid_and_symbol(self, msgid: str, symbol: str) -> None:
  40. """Add valid message id.
  41. There is a little duplication with add_legacy_msgid_and_symbol to avoid a function call,
  42. this is called a lot at initialization."""
  43. self.__msgid_to_symbol[msgid] = symbol
  44. self.__symbol_to_msgid[symbol] = msgid
  45. def add_legacy_msgid_and_symbol(
  46. self, msgid: str, symbol: str, new_msgid: str
  47. ) -> None:
  48. """Add valid legacy message id.
  49. There is a little duplication with add_msgid_and_symbol to avoid a function call,
  50. this is called a lot at initialization."""
  51. self.__msgid_to_symbol[msgid] = symbol
  52. self.__symbol_to_msgid[symbol] = msgid
  53. existing_old_names = self.__old_names.get(msgid, [])
  54. existing_old_names.append(new_msgid)
  55. self.__old_names[msgid] = existing_old_names
  56. def check_msgid_and_symbol(self, msgid: str, symbol: str) -> None:
  57. existing_msgid: Optional[str] = self.__symbol_to_msgid.get(symbol)
  58. existing_symbol: Optional[str] = self.__msgid_to_symbol.get(msgid)
  59. if existing_symbol is None and existing_msgid is None:
  60. return # both symbol and msgid are usable
  61. if existing_msgid is not None:
  62. if existing_msgid != msgid:
  63. self._raise_duplicate_msgid(symbol, msgid, existing_msgid)
  64. if existing_symbol and existing_symbol != symbol:
  65. # See https://github.com/python/mypy/issues/10559
  66. self._raise_duplicate_symbol(msgid, symbol, existing_symbol)
  67. @staticmethod
  68. def _raise_duplicate_symbol(msgid: str, symbol: str, other_symbol: str) -> NoReturn:
  69. """Raise an error when a symbol is duplicated."""
  70. symbols = [symbol, other_symbol]
  71. symbols.sort()
  72. error_message = f"Message id '{msgid}' cannot have both "
  73. error_message += f"'{symbols[0]}' and '{symbols[1]}' as symbolic name."
  74. raise InvalidMessageError(error_message)
  75. @staticmethod
  76. def _raise_duplicate_msgid(symbol: str, msgid: str, other_msgid: str) -> NoReturn:
  77. """Raise an error when a msgid is duplicated."""
  78. msgids = [msgid, other_msgid]
  79. msgids.sort()
  80. error_message = (
  81. f"Message symbol '{symbol}' cannot be used for "
  82. f"'{msgids[0]}' and '{msgids[1]}' at the same time."
  83. f" If you're creating an 'old_names' use 'old-{symbol}' as the old symbol."
  84. )
  85. raise InvalidMessageError(error_message)
  86. def get_active_msgids(self, msgid_or_symbol: str) -> List[str]:
  87. """Return msgids but the input can be a symbol."""
  88. # Only msgid can have a digit as second letter
  89. is_msgid: bool = msgid_or_symbol[1:].isdigit()
  90. msgid = None
  91. if is_msgid:
  92. msgid = msgid_or_symbol.upper()
  93. symbol = self.__msgid_to_symbol.get(msgid)
  94. else:
  95. msgid = self.__symbol_to_msgid.get(msgid_or_symbol)
  96. symbol = msgid_or_symbol
  97. if msgid is None or symbol is None or not msgid or not symbol:
  98. error_msg = f"No such message id or symbol '{msgid_or_symbol}'."
  99. raise UnknownMessageError(error_msg)
  100. return self.__old_names.get(msgid, [msgid])