Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/dulwich/reflog.py: 19%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

99 statements  

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 

22"""Utilities for reading and generating reflogs.""" 

23 

24__all__ = [ 

25 "drop_reflog_entry", 

26 "expire_reflog", 

27 "format_reflog_line", 

28 "iter_reflogs", 

29 "parse_reflog_line", 

30 "parse_reflog_spec", 

31 "read_reflog", 

32] 

33 

34import collections 

35import os 

36from collections.abc import Callable, Generator 

37from pathlib import Path 

38from typing import IO, BinaryIO 

39 

40from .file import _GitFile 

41from .objects import ZERO_SHA, format_timezone, parse_timezone 

42 

43Entry = collections.namedtuple( 

44 "Entry", 

45 ["old_sha", "new_sha", "committer", "timestamp", "timezone", "message"], 

46) 

47 

48 

49def parse_reflog_spec(refspec: str | bytes) -> tuple[bytes, int]: 

50 """Parse a reflog specification like 'HEAD@{1}' or 'refs/heads/master@{2}'. 

51 

52 Args: 

53 refspec: Reflog specification (e.g., 'HEAD@{1}', 'master@{0}') 

54 

55 Returns: 

56 Tuple of (ref_name, index) where index is in Git reflog order (0 = newest) 

57 

58 Raises: 

59 ValueError: If the refspec is not a valid reflog specification 

60 """ 

61 if isinstance(refspec, str): 

62 refspec = refspec.encode("utf-8") 

63 

64 if b"@{" not in refspec: 

65 raise ValueError( 

66 f"Invalid reflog spec: {refspec!r}. Expected format: ref@{{n}}" 

67 ) 

68 

69 ref, rest = refspec.split(b"@{", 1) 

70 if not rest.endswith(b"}"): 

71 raise ValueError( 

72 f"Invalid reflog spec: {refspec!r}. Expected format: ref@{{n}}" 

73 ) 

74 

75 index_str = rest[:-1] 

76 if not index_str.isdigit(): 

77 raise ValueError( 

78 f"Invalid reflog index: {index_str!r}. Expected integer in ref@{{n}}" 

79 ) 

80 

81 # Use HEAD if no ref specified (e.g., "@{1}") 

82 if not ref: 

83 ref = b"HEAD" 

84 

85 return ref, int(index_str) 

86 

87 

88def format_reflog_line( 

89 old_sha: bytes | None, 

90 new_sha: bytes, 

91 committer: bytes, 

92 timestamp: int | float, 

93 timezone: int, 

94 message: bytes, 

95) -> bytes: 

96 """Generate a single reflog line. 

97 

98 Args: 

99 old_sha: Old Commit SHA 

100 new_sha: New Commit SHA 

101 committer: Committer name and e-mail 

102 timestamp: Timestamp 

103 timezone: Timezone 

104 message: Message 

105 """ 

106 if old_sha is None: 

107 old_sha = ZERO_SHA 

108 return ( 

109 old_sha 

110 + b" " 

111 + new_sha 

112 + b" " 

113 + committer 

114 + b" " 

115 + str(int(timestamp)).encode("ascii") 

116 + b" " 

117 + format_timezone(timezone) 

118 + b"\t" 

119 + message 

120 ) 

121 

122 

123def parse_reflog_line(line: bytes) -> Entry: 

124 """Parse a reflog line. 

125 

126 Args: 

127 line: Line to parse 

128 Returns: Tuple of (old_sha, new_sha, committer, timestamp, timezone, 

129 message) 

130 """ 

131 (begin, message) = line.split(b"\t", 1) 

132 (old_sha, new_sha, rest) = begin.split(b" ", 2) 

133 (committer, timestamp_str, timezone_str) = rest.rsplit(b" ", 2) 

134 return Entry( 

135 old_sha, 

136 new_sha, 

137 committer, 

138 int(timestamp_str), 

139 parse_timezone(timezone_str)[0], 

140 message, 

141 ) 

142 

143 

144def read_reflog( 

145 f: BinaryIO | IO[bytes] | _GitFile, 

146) -> Generator[Entry, None, None]: 

147 """Read reflog. 

148 

149 Args: 

150 f: File-like object 

151 Returns: Iterator over Entry objects 

152 """ 

153 for line in f: 

154 yield parse_reflog_line(line.rstrip(b"\n")) 

155 

156 

157def drop_reflog_entry(f: BinaryIO, index: int, rewrite: bool = False) -> None: 

158 """Drop the specified reflog entry. 

159 

160 Args: 

161 f: File-like object 

162 index: Reflog entry index (in Git reflog reverse 0-indexed order) 

163 rewrite: If a reflog entry's predecessor is removed, set its 

164 old SHA to the new SHA of the entry that now precedes it 

165 """ 

166 if index < 0: 

167 raise ValueError(f"Invalid reflog index {index}") 

168 

169 log = [] 

170 offset = f.tell() 

171 for line in f: 

172 log.append((offset, parse_reflog_line(line))) 

173 offset = f.tell() 

174 

175 inverse_index = len(log) - index - 1 

176 write_offset = log[inverse_index][0] 

177 f.seek(write_offset) 

178 

179 if index == 0: 

180 f.truncate() 

181 return 

182 

183 del log[inverse_index] 

184 if rewrite and index > 0 and log: 

185 if inverse_index == 0: 

186 previous_new = ZERO_SHA 

187 else: 

188 previous_new = log[inverse_index - 1][1].new_sha 

189 offset, entry = log[inverse_index] 

190 log[inverse_index] = ( 

191 offset, 

192 Entry( 

193 previous_new, 

194 entry.new_sha, 

195 entry.committer, 

196 entry.timestamp, 

197 entry.timezone, 

198 entry.message, 

199 ), 

200 ) 

201 

202 for _, entry in log[inverse_index:]: 

203 f.write( 

204 format_reflog_line( 

205 entry.old_sha, 

206 entry.new_sha, 

207 entry.committer, 

208 entry.timestamp, 

209 entry.timezone, 

210 entry.message, 

211 ) 

212 ) 

213 f.truncate() 

214 

215 

216def expire_reflog( 

217 f: BinaryIO, 

218 expire_time: int | None = None, 

219 expire_unreachable_time: int | None = None, 

220 reachable_checker: Callable[[bytes], bool] | None = None, 

221) -> int: 

222 """Expire reflog entries based on age and reachability. 

223 

224 Args: 

225 f: File-like object for the reflog 

226 expire_time: Expire entries older than this timestamp (seconds since epoch). 

227 If None, entries are not expired based on age alone. 

228 expire_unreachable_time: Expire unreachable entries older than this 

229 timestamp. If None, unreachable entries are not expired. 

230 reachable_checker: Optional callable that takes a SHA and returns True 

231 if the commit is reachable. If None, all entries are considered 

232 reachable. 

233 

234 Returns: 

235 Number of entries expired 

236 """ 

237 if expire_time is None and expire_unreachable_time is None: 

238 return 0 

239 

240 entries = [] 

241 offset = f.tell() 

242 for line in f: 

243 entries.append((offset, parse_reflog_line(line))) 

244 offset = f.tell() 

245 

246 # Filter entries that should be kept 

247 kept_entries = [] 

248 expired_count = 0 

249 

250 for offset, entry in entries: 

251 should_expire = False 

252 

253 # Check if entry is reachable 

254 is_reachable = True 

255 if reachable_checker is not None: 

256 is_reachable = reachable_checker(entry.new_sha) 

257 

258 # Apply expiration rules 

259 # Check the appropriate expiration time based on reachability 

260 if is_reachable: 

261 if expire_time is not None and entry.timestamp < expire_time: 

262 should_expire = True 

263 else: 

264 if ( 

265 expire_unreachable_time is not None 

266 and entry.timestamp < expire_unreachable_time 

267 ): 

268 should_expire = True 

269 

270 if should_expire: 

271 expired_count += 1 

272 else: 

273 kept_entries.append((offset, entry)) 

274 

275 # Write back the kept entries 

276 if expired_count > 0: 

277 f.seek(0) 

278 for _, entry in kept_entries: 

279 f.write( 

280 format_reflog_line( 

281 entry.old_sha, 

282 entry.new_sha, 

283 entry.committer, 

284 entry.timestamp, 

285 entry.timezone, 

286 entry.message, 

287 ) 

288 ) 

289 f.truncate() 

290 

291 return expired_count 

292 

293 

294def iter_reflogs(logs_dir: str) -> Generator[bytes, None, None]: 

295 """Iterate over all reflogs in a repository. 

296 

297 Args: 

298 logs_dir: Path to the logs directory (e.g., .git/logs) 

299 

300 Yields: 

301 Reference names (as bytes) that have reflogs 

302 """ 

303 if not os.path.exists(logs_dir): 

304 return 

305 

306 logs_path = Path(logs_dir) 

307 for log_file in logs_path.rglob("*"): 

308 if log_file.is_file(): 

309 # Get the ref name by removing the logs_dir prefix 

310 ref_name = str(log_file.relative_to(logs_path)) 

311 # Convert path separators to / for refs 

312 ref_name = ref_name.replace(os.sep, "/") 

313 yield ref_name.encode("utf-8")