reflog.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. # reflog.py -- Parsing and writing reflog files
  2. # Copyright (C) 2015 Jelmer Vernooij and others.
  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. """Utilities for reading and generating reflogs."""
  22. import collections
  23. from collections.abc import Callable, Generator
  24. from typing import IO, BinaryIO, Optional, Union
  25. from .file import _GitFile
  26. from .objects import ZERO_SHA, format_timezone, parse_timezone
  27. Entry = collections.namedtuple(
  28. "Entry",
  29. ["old_sha", "new_sha", "committer", "timestamp", "timezone", "message"],
  30. )
  31. def parse_reflog_spec(refspec: Union[str, bytes]) -> tuple[bytes, int]:
  32. """Parse a reflog specification like 'HEAD@{1}' or 'refs/heads/master@{2}'.
  33. Args:
  34. refspec: Reflog specification (e.g., 'HEAD@{1}', 'master@{0}')
  35. Returns:
  36. Tuple of (ref_name, index) where index is in Git reflog order (0 = newest)
  37. Raises:
  38. ValueError: If the refspec is not a valid reflog specification
  39. """
  40. if isinstance(refspec, str):
  41. refspec = refspec.encode("utf-8")
  42. if b"@{" not in refspec:
  43. raise ValueError(
  44. f"Invalid reflog spec: {refspec!r}. Expected format: ref@{{n}}"
  45. )
  46. ref, rest = refspec.split(b"@{", 1)
  47. if not rest.endswith(b"}"):
  48. raise ValueError(
  49. f"Invalid reflog spec: {refspec!r}. Expected format: ref@{{n}}"
  50. )
  51. index_str = rest[:-1]
  52. if not index_str.isdigit():
  53. raise ValueError(
  54. f"Invalid reflog index: {index_str!r}. Expected integer in ref@{{n}}"
  55. )
  56. # Use HEAD if no ref specified (e.g., "@{1}")
  57. if not ref:
  58. ref = b"HEAD"
  59. return ref, int(index_str)
  60. def format_reflog_line(
  61. old_sha: Optional[bytes],
  62. new_sha: bytes,
  63. committer: bytes,
  64. timestamp: Union[int, float],
  65. timezone: int,
  66. message: bytes,
  67. ) -> bytes:
  68. """Generate a single reflog line.
  69. Args:
  70. old_sha: Old Commit SHA
  71. new_sha: New Commit SHA
  72. committer: Committer name and e-mail
  73. timestamp: Timestamp
  74. timezone: Timezone
  75. message: Message
  76. """
  77. if old_sha is None:
  78. old_sha = ZERO_SHA
  79. return (
  80. old_sha
  81. + b" "
  82. + new_sha
  83. + b" "
  84. + committer
  85. + b" "
  86. + str(int(timestamp)).encode("ascii")
  87. + b" "
  88. + format_timezone(timezone)
  89. + b"\t"
  90. + message
  91. )
  92. def parse_reflog_line(line: bytes) -> Entry:
  93. """Parse a reflog line.
  94. Args:
  95. line: Line to parse
  96. Returns: Tuple of (old_sha, new_sha, committer, timestamp, timezone,
  97. message)
  98. """
  99. (begin, message) = line.split(b"\t", 1)
  100. (old_sha, new_sha, rest) = begin.split(b" ", 2)
  101. (committer, timestamp_str, timezone_str) = rest.rsplit(b" ", 2)
  102. return Entry(
  103. old_sha,
  104. new_sha,
  105. committer,
  106. int(timestamp_str),
  107. parse_timezone(timezone_str)[0],
  108. message,
  109. )
  110. def read_reflog(
  111. f: Union[BinaryIO, IO[bytes], _GitFile],
  112. ) -> Generator[Entry, None, None]:
  113. """Read reflog.
  114. Args:
  115. f: File-like object
  116. Returns: Iterator over Entry objects
  117. """
  118. for line in f:
  119. yield parse_reflog_line(line.rstrip(b"\n"))
  120. def drop_reflog_entry(f: BinaryIO, index: int, rewrite: bool = False) -> None:
  121. """Drop the specified reflog entry.
  122. Args:
  123. f: File-like object
  124. index: Reflog entry index (in Git reflog reverse 0-indexed order)
  125. rewrite: If a reflog entry's predecessor is removed, set its
  126. old SHA to the new SHA of the entry that now precedes it
  127. """
  128. if index < 0:
  129. raise ValueError(f"Invalid reflog index {index}")
  130. log = []
  131. offset = f.tell()
  132. for line in f:
  133. log.append((offset, parse_reflog_line(line)))
  134. offset = f.tell()
  135. inverse_index = len(log) - index - 1
  136. write_offset = log[inverse_index][0]
  137. f.seek(write_offset)
  138. if index == 0:
  139. f.truncate()
  140. return
  141. del log[inverse_index]
  142. if rewrite and index > 0 and log:
  143. if inverse_index == 0:
  144. previous_new = ZERO_SHA
  145. else:
  146. previous_new = log[inverse_index - 1][1].new_sha
  147. offset, entry = log[inverse_index]
  148. log[inverse_index] = (
  149. offset,
  150. Entry(
  151. previous_new,
  152. entry.new_sha,
  153. entry.committer,
  154. entry.timestamp,
  155. entry.timezone,
  156. entry.message,
  157. ),
  158. )
  159. for _, entry in log[inverse_index:]:
  160. f.write(
  161. format_reflog_line(
  162. entry.old_sha,
  163. entry.new_sha,
  164. entry.committer,
  165. entry.timestamp,
  166. entry.timezone,
  167. entry.message,
  168. )
  169. )
  170. f.truncate()
  171. def expire_reflog(
  172. f: BinaryIO,
  173. expire_time: Optional[int] = None,
  174. expire_unreachable_time: Optional[int] = None,
  175. # String annotation to work around typing module bug in Python 3.9.0/3.9.1
  176. # See: https://github.com/jelmer/dulwich/issues/1948
  177. reachable_checker: "Optional[Callable[[bytes], bool]]" = None,
  178. ) -> int:
  179. """Expire reflog entries based on age and reachability.
  180. Args:
  181. f: File-like object for the reflog
  182. expire_time: Expire entries older than this timestamp (seconds since epoch).
  183. If None, entries are not expired based on age alone.
  184. expire_unreachable_time: Expire unreachable entries older than this
  185. timestamp. If None, unreachable entries are not expired.
  186. reachable_checker: Optional callable that takes a SHA and returns True
  187. if the commit is reachable. If None, all entries are considered
  188. reachable.
  189. Returns:
  190. Number of entries expired
  191. """
  192. if expire_time is None and expire_unreachable_time is None:
  193. return 0
  194. entries = []
  195. offset = f.tell()
  196. for line in f:
  197. entries.append((offset, parse_reflog_line(line)))
  198. offset = f.tell()
  199. # Filter entries that should be kept
  200. kept_entries = []
  201. expired_count = 0
  202. for offset, entry in entries:
  203. should_expire = False
  204. # Check if entry is reachable
  205. is_reachable = True
  206. if reachable_checker is not None:
  207. is_reachable = reachable_checker(entry.new_sha)
  208. # Apply expiration rules
  209. # Check the appropriate expiration time based on reachability
  210. if is_reachable:
  211. if expire_time is not None and entry.timestamp < expire_time:
  212. should_expire = True
  213. else:
  214. if (
  215. expire_unreachable_time is not None
  216. and entry.timestamp < expire_unreachable_time
  217. ):
  218. should_expire = True
  219. if should_expire:
  220. expired_count += 1
  221. else:
  222. kept_entries.append((offset, entry))
  223. # Write back the kept entries
  224. if expired_count > 0:
  225. f.seek(0)
  226. for _, entry in kept_entries:
  227. f.write(
  228. format_reflog_line(
  229. entry.old_sha,
  230. entry.new_sha,
  231. entry.committer,
  232. entry.timestamp,
  233. entry.timezone,
  234. entry.message,
  235. )
  236. )
  237. f.truncate()
  238. return expired_count
  239. def iter_reflogs(logs_dir: str) -> Generator[bytes, None, None]:
  240. """Iterate over all reflogs in a repository.
  241. Args:
  242. logs_dir: Path to the logs directory (e.g., .git/logs)
  243. Yields:
  244. Reference names (as bytes) that have reflogs
  245. """
  246. import os
  247. from pathlib import Path
  248. if not os.path.exists(logs_dir):
  249. return
  250. logs_path = Path(logs_dir)
  251. for log_file in logs_path.rglob("*"):
  252. if log_file.is_file():
  253. # Get the ref name by removing the logs_dir prefix
  254. ref_name = str(log_file.relative_to(logs_path))
  255. # Convert path separators to / for refs
  256. ref_name = ref_name.replace(os.sep, "/")
  257. yield ref_name.encode("utf-8")