reflog.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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
  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: 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: bytes | None,
  62. new_sha: bytes,
  63. committer: bytes,
  64. timestamp: 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: 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: int | None = None,
  174. expire_unreachable_time: int | None = None,
  175. reachable_checker: Callable[[bytes], bool] | None = None,
  176. ) -> int:
  177. """Expire reflog entries based on age and reachability.
  178. Args:
  179. f: File-like object for the reflog
  180. expire_time: Expire entries older than this timestamp (seconds since epoch).
  181. If None, entries are not expired based on age alone.
  182. expire_unreachable_time: Expire unreachable entries older than this
  183. timestamp. If None, unreachable entries are not expired.
  184. reachable_checker: Optional callable that takes a SHA and returns True
  185. if the commit is reachable. If None, all entries are considered
  186. reachable.
  187. Returns:
  188. Number of entries expired
  189. """
  190. if expire_time is None and expire_unreachable_time is None:
  191. return 0
  192. entries = []
  193. offset = f.tell()
  194. for line in f:
  195. entries.append((offset, parse_reflog_line(line)))
  196. offset = f.tell()
  197. # Filter entries that should be kept
  198. kept_entries = []
  199. expired_count = 0
  200. for offset, entry in entries:
  201. should_expire = False
  202. # Check if entry is reachable
  203. is_reachable = True
  204. if reachable_checker is not None:
  205. is_reachable = reachable_checker(entry.new_sha)
  206. # Apply expiration rules
  207. # Check the appropriate expiration time based on reachability
  208. if is_reachable:
  209. if expire_time is not None and entry.timestamp < expire_time:
  210. should_expire = True
  211. else:
  212. if (
  213. expire_unreachable_time is not None
  214. and entry.timestamp < expire_unreachable_time
  215. ):
  216. should_expire = True
  217. if should_expire:
  218. expired_count += 1
  219. else:
  220. kept_entries.append((offset, entry))
  221. # Write back the kept entries
  222. if expired_count > 0:
  223. f.seek(0)
  224. for _, entry in kept_entries:
  225. f.write(
  226. format_reflog_line(
  227. entry.old_sha,
  228. entry.new_sha,
  229. entry.committer,
  230. entry.timestamp,
  231. entry.timezone,
  232. entry.message,
  233. )
  234. )
  235. f.truncate()
  236. return expired_count
  237. def iter_reflogs(logs_dir: str) -> Generator[bytes, None, None]:
  238. """Iterate over all reflogs in a repository.
  239. Args:
  240. logs_dir: Path to the logs directory (e.g., .git/logs)
  241. Yields:
  242. Reference names (as bytes) that have reflogs
  243. """
  244. import os
  245. from pathlib import Path
  246. if not os.path.exists(logs_dir):
  247. return
  248. logs_path = Path(logs_dir)
  249. for log_file in logs_path.rglob("*"):
  250. if log_file.is_file():
  251. # Get the ref name by removing the logs_dir prefix
  252. ref_name = str(log_file.relative_to(logs_path))
  253. # Convert path separators to / for refs
  254. ref_name = ref_name.replace(os.sep, "/")
  255. yield ref_name.encode("utf-8")