mailmap.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # mailmap.py -- Mailmap reader
  2. # Copyright (C) 2018 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Mailmap file reader."""
  22. from collections.abc import Iterator
  23. from typing import IO, Optional, Union
  24. def parse_identity(text: bytes) -> tuple[Optional[bytes], Optional[bytes]]:
  25. """Parse an identity string into name and email.
  26. Args:
  27. text: Identity string in format "Name <email>"
  28. Returns:
  29. Tuple of (name, email) where either can be None
  30. """
  31. # TODO(jelmer): Integrate this with dulwich.fastexport.split_email and
  32. # dulwich.repo.check_user_identity
  33. (name_str, email_str) = text.rsplit(b"<", 1)
  34. name_str = name_str.strip()
  35. email_str = email_str.rstrip(b">").strip()
  36. name: Optional[bytes] = name_str if name_str else None
  37. email: Optional[bytes] = email_str if email_str else None
  38. return (name, email)
  39. def read_mailmap(
  40. f: IO[bytes],
  41. ) -> Iterator[
  42. tuple[
  43. tuple[Optional[bytes], Optional[bytes]],
  44. Optional[tuple[Optional[bytes], Optional[bytes]]],
  45. ]
  46. ]:
  47. """Read a mailmap.
  48. Args:
  49. f: File-like object to read from
  50. Returns: Iterator over
  51. ((canonical_name, canonical_email), (from_name, from_email)) tuples
  52. """
  53. for line in f:
  54. # Remove comments
  55. line = line.split(b"#")[0]
  56. line = line.strip()
  57. if not line:
  58. continue
  59. (canonical_identity, from_identity) = line.split(b">", 1)
  60. canonical_identity += b">"
  61. if from_identity.strip():
  62. parsed_from_identity = parse_identity(from_identity)
  63. else:
  64. parsed_from_identity = None
  65. parsed_canonical_identity = parse_identity(canonical_identity)
  66. yield parsed_canonical_identity, parsed_from_identity
  67. class Mailmap:
  68. """Class for accessing a mailmap file."""
  69. def __init__(
  70. self,
  71. map: Optional[
  72. Iterator[
  73. tuple[
  74. tuple[Optional[bytes], Optional[bytes]],
  75. Optional[tuple[Optional[bytes], Optional[bytes]]],
  76. ]
  77. ]
  78. ] = None,
  79. ) -> None:
  80. """Initialize Mailmap.
  81. Args:
  82. map: Optional iterator of (canonical_identity, from_identity) tuples
  83. """
  84. self._table: dict[
  85. tuple[Optional[bytes], Optional[bytes]],
  86. tuple[Optional[bytes], Optional[bytes]],
  87. ] = {}
  88. if map:
  89. for canonical_identity, from_identity in map:
  90. self.add_entry(canonical_identity, from_identity)
  91. def add_entry(
  92. self,
  93. canonical_identity: tuple[Optional[bytes], Optional[bytes]],
  94. from_identity: Optional[tuple[Optional[bytes], Optional[bytes]]] = None,
  95. ) -> None:
  96. """Add an entry to the mail mail.
  97. Any of the fields can be None, but at least one of them needs to be
  98. set.
  99. Args:
  100. canonical_identity: The canonical identity (tuple)
  101. from_identity: The from identity (tuple)
  102. """
  103. if from_identity is None:
  104. from_name, from_email = None, None
  105. else:
  106. (from_name, from_email) = from_identity
  107. (canonical_name, canonical_email) = canonical_identity
  108. if from_name is None and from_email is None:
  109. self._table[canonical_name, None] = canonical_identity
  110. self._table[None, canonical_email] = canonical_identity
  111. else:
  112. self._table[from_name, from_email] = canonical_identity
  113. def lookup(
  114. self, identity: Union[bytes, tuple[Optional[bytes], Optional[bytes]]]
  115. ) -> Union[bytes, tuple[Optional[bytes], Optional[bytes]]]:
  116. """Lookup an identity in this mailmail."""
  117. if not isinstance(identity, tuple):
  118. was_tuple = False
  119. identity = parse_identity(identity)
  120. else:
  121. was_tuple = True
  122. for query in [identity, (None, identity[1]), (identity[0], None)]:
  123. canonical_identity = self._table.get(query)
  124. if canonical_identity is not None:
  125. identity = (
  126. canonical_identity[0] or identity[0],
  127. canonical_identity[1] or identity[1],
  128. )
  129. break
  130. if was_tuple:
  131. return identity
  132. else:
  133. name, email = identity
  134. if name is None:
  135. name = b""
  136. if email is None:
  137. email = b""
  138. return name + b" <" + email + b">"
  139. @classmethod
  140. def from_path(cls, path: str) -> "Mailmap":
  141. """Create Mailmap from file path.
  142. Args:
  143. path: Path to mailmap file
  144. Returns:
  145. Mailmap instance
  146. """
  147. with open(path, "rb") as f:
  148. return cls(read_mailmap(f))