protocol.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. # protocol.py -- Shared parts of the git protocols
  2. # Copyright (C) 2008 John Carr <john.carr@unrouted.co.uk>
  3. # Copyright (C) 2008-2012 Jelmer Vernooij <jelmer@jelmer.uk>
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  7. # General Public License as published by the Free Software Foundation; version 2.0
  8. # or (at your option) any later version. You can redistribute it and/or
  9. # modify it under the terms of either of these two licenses.
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # You should have received a copy of the licenses; if not, see
  18. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  19. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  20. # License, Version 2.0.
  21. #
  22. """Generic functions for talking the git smart server protocol."""
  23. import types
  24. from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
  25. from io import BytesIO
  26. from os import SEEK_END
  27. from typing import TYPE_CHECKING
  28. import dulwich
  29. from .errors import GitProtocolError, HangupException
  30. from .objects import ObjectID
  31. if TYPE_CHECKING:
  32. from .pack import ObjectContainer
  33. from .refs import Ref
  34. TCP_GIT_PORT = 9418
  35. # Git protocol version 0 is the original Git protocol, which lacked a
  36. # version number until Git protocol version 1 was introduced by Brandon
  37. # Williams in 2017.
  38. #
  39. # Protocol version 1 is simply the original v0 protocol with the addition of
  40. # a single packet line, which precedes the ref advertisement, indicating the
  41. # protocol version being used. This was done in preparation for protocol v2.
  42. #
  43. # Git protocol version 2 was first introduced by Brandon Williams in 2018 and
  44. # adds many features. See the gitprotocol-v2(5) manual page for details.
  45. # As of 2024, Git only implements version 2 during 'git fetch' and still uses
  46. # version 0 during 'git push'.
  47. GIT_PROTOCOL_VERSIONS = [0, 1, 2]
  48. DEFAULT_GIT_PROTOCOL_VERSION_FETCH = 2
  49. DEFAULT_GIT_PROTOCOL_VERSION_SEND = 0
  50. # Suffix used in the Git protocol to indicate peeled tag references
  51. PEELED_TAG_SUFFIX = b"^{}"
  52. ZERO_SHA: ObjectID = ObjectID(b"0" * 40)
  53. SINGLE_ACK = 0
  54. MULTI_ACK = 1
  55. MULTI_ACK_DETAILED = 2
  56. # pack data
  57. SIDE_BAND_CHANNEL_DATA = 1
  58. # progress messages
  59. SIDE_BAND_CHANNEL_PROGRESS = 2
  60. # fatal error message just before stream aborts
  61. SIDE_BAND_CHANNEL_FATAL = 3
  62. CAPABILITY_ATOMIC = b"atomic"
  63. CAPABILITY_DEEPEN_SINCE = b"deepen-since"
  64. CAPABILITY_DEEPEN_NOT = b"deepen-not"
  65. CAPABILITY_DEEPEN_RELATIVE = b"deepen-relative"
  66. CAPABILITY_DELETE_REFS = b"delete-refs"
  67. CAPABILITY_INCLUDE_TAG = b"include-tag"
  68. CAPABILITY_MULTI_ACK = b"multi_ack"
  69. CAPABILITY_MULTI_ACK_DETAILED = b"multi_ack_detailed"
  70. CAPABILITY_NO_DONE = b"no-done"
  71. CAPABILITY_NO_PROGRESS = b"no-progress"
  72. CAPABILITY_OFS_DELTA = b"ofs-delta"
  73. CAPABILITY_QUIET = b"quiet"
  74. CAPABILITY_REPORT_STATUS = b"report-status"
  75. CAPABILITY_SHALLOW = b"shallow"
  76. CAPABILITY_SIDE_BAND = b"side-band"
  77. CAPABILITY_SIDE_BAND_64K = b"side-band-64k"
  78. CAPABILITY_THIN_PACK = b"thin-pack"
  79. CAPABILITY_AGENT = b"agent"
  80. CAPABILITY_SYMREF = b"symref"
  81. CAPABILITY_ALLOW_TIP_SHA1_IN_WANT = b"allow-tip-sha1-in-want"
  82. CAPABILITY_ALLOW_REACHABLE_SHA1_IN_WANT = b"allow-reachable-sha1-in-want"
  83. CAPABILITY_FETCH = b"fetch"
  84. CAPABILITY_FILTER = b"filter"
  85. # Magic ref that is used to attach capabilities to when
  86. # there are no refs. Should always be ste to ZERO_SHA.
  87. CAPABILITIES_REF = b"capabilities^{}"
  88. COMMON_CAPABILITIES = [
  89. CAPABILITY_OFS_DELTA,
  90. CAPABILITY_SIDE_BAND,
  91. CAPABILITY_SIDE_BAND_64K,
  92. CAPABILITY_AGENT,
  93. CAPABILITY_NO_PROGRESS,
  94. ]
  95. KNOWN_UPLOAD_CAPABILITIES = set(
  96. [
  97. *COMMON_CAPABILITIES,
  98. CAPABILITY_THIN_PACK,
  99. CAPABILITY_MULTI_ACK,
  100. CAPABILITY_MULTI_ACK_DETAILED,
  101. CAPABILITY_INCLUDE_TAG,
  102. CAPABILITY_DEEPEN_SINCE,
  103. CAPABILITY_SYMREF,
  104. CAPABILITY_SHALLOW,
  105. CAPABILITY_DEEPEN_NOT,
  106. CAPABILITY_DEEPEN_RELATIVE,
  107. CAPABILITY_ALLOW_TIP_SHA1_IN_WANT,
  108. CAPABILITY_ALLOW_REACHABLE_SHA1_IN_WANT,
  109. CAPABILITY_FETCH,
  110. ]
  111. )
  112. KNOWN_RECEIVE_CAPABILITIES = set(
  113. [
  114. *COMMON_CAPABILITIES,
  115. CAPABILITY_REPORT_STATUS,
  116. CAPABILITY_DELETE_REFS,
  117. CAPABILITY_QUIET,
  118. CAPABILITY_ATOMIC,
  119. ]
  120. )
  121. DEPTH_INFINITE = 0x7FFFFFFF
  122. NAK_LINE = b"NAK\n"
  123. def agent_string() -> bytes:
  124. """Generate the agent string for dulwich.
  125. Returns:
  126. Agent string as bytes
  127. """
  128. return ("dulwich/" + ".".join(map(str, dulwich.__version__))).encode("ascii")
  129. def capability_agent() -> bytes:
  130. """Generate the agent capability string.
  131. Returns:
  132. Agent capability with dulwich version
  133. """
  134. return CAPABILITY_AGENT + b"=" + agent_string()
  135. def capability_symref(from_ref: bytes, to_ref: bytes) -> bytes:
  136. """Generate a symref capability string.
  137. Args:
  138. from_ref: Source reference name
  139. to_ref: Target reference name
  140. Returns:
  141. Symref capability string
  142. """
  143. return CAPABILITY_SYMREF + b"=" + from_ref + b":" + to_ref
  144. def extract_capability_names(capabilities: Iterable[bytes]) -> set[bytes]:
  145. """Extract capability names from a list of capabilities.
  146. Args:
  147. capabilities: List of capability strings
  148. Returns:
  149. Set of capability names
  150. """
  151. return {parse_capability(c)[0] for c in capabilities}
  152. def parse_capability(capability: bytes) -> tuple[bytes, bytes | None]:
  153. """Parse a capability string into name and value.
  154. Args:
  155. capability: Capability string
  156. Returns:
  157. Tuple of (capability_name, capability_value)
  158. """
  159. parts = capability.split(b"=", 1)
  160. if len(parts) == 1:
  161. return (parts[0], None)
  162. return (parts[0], parts[1])
  163. def symref_capabilities(symrefs: Iterable[tuple[bytes, bytes]]) -> list[bytes]:
  164. """Generate symref capability strings from symref pairs.
  165. Args:
  166. symrefs: Iterable of (from_ref, to_ref) tuples
  167. Returns:
  168. List of symref capability strings
  169. """
  170. return [capability_symref(*k) for k in symrefs]
  171. COMMAND_DEEPEN = b"deepen"
  172. COMMAND_DEEPEN_SINCE = b"deepen-since"
  173. COMMAND_DEEPEN_NOT = b"deepen-not"
  174. COMMAND_SHALLOW = b"shallow"
  175. COMMAND_UNSHALLOW = b"unshallow"
  176. COMMAND_DONE = b"done"
  177. COMMAND_WANT = b"want"
  178. COMMAND_HAVE = b"have"
  179. def format_cmd_pkt(cmd: bytes, *args: bytes) -> bytes:
  180. """Format a command packet.
  181. Args:
  182. cmd: Command name
  183. *args: Command arguments
  184. Returns:
  185. Formatted command packet
  186. """
  187. return cmd + b" " + b"".join([(a + b"\0") for a in args])
  188. def parse_cmd_pkt(line: bytes) -> tuple[bytes, list[bytes]]:
  189. """Parse a command packet.
  190. Args:
  191. line: Command line to parse
  192. Returns:
  193. Tuple of (command, [arguments])
  194. """
  195. splice_at = line.find(b" ")
  196. cmd, args = line[:splice_at], line[splice_at + 1 :]
  197. assert args[-1:] == b"\x00"
  198. return cmd, args[:-1].split(b"\0")
  199. def pkt_line(data: bytes | None) -> bytes:
  200. """Wrap data in a pkt-line.
  201. Args:
  202. data: The data to wrap, as a str or None.
  203. Returns: The data prefixed with its length in pkt-line format; if data was
  204. None, returns the flush-pkt ('0000').
  205. """
  206. if data is None:
  207. return b"0000"
  208. return f"{len(data) + 4:04x}".encode("ascii") + data
  209. def pkt_seq(*seq: bytes | None) -> bytes:
  210. """Wrap a sequence of data in pkt-lines.
  211. Args:
  212. seq: An iterable of strings to wrap.
  213. """
  214. return b"".join([pkt_line(s) for s in seq]) + pkt_line(None)
  215. class Protocol:
  216. """Class for interacting with a remote git process over the wire.
  217. Parts of the git wire protocol use 'pkt-lines' to communicate. A pkt-line
  218. consists of the length of the line as a 4-byte hex string, followed by the
  219. payload data. The length includes the 4-byte header. The special line
  220. '0000' indicates the end of a section of input and is called a 'flush-pkt'.
  221. For details on the pkt-line format, see the cgit distribution:
  222. Documentation/technical/protocol-common.txt
  223. """
  224. def __init__(
  225. self,
  226. read: Callable[[int], bytes],
  227. write: Callable[[bytes], int | None],
  228. close: Callable[[], None] | None = None,
  229. report_activity: Callable[[int, str], None] | None = None,
  230. ) -> None:
  231. """Initialize Protocol.
  232. Args:
  233. read: Function to read bytes from the transport
  234. write: Function to write bytes to the transport
  235. close: Optional function to close the transport
  236. report_activity: Optional function to report activity
  237. """
  238. self.read = read
  239. self.write = write
  240. self._close = close
  241. self.report_activity = report_activity
  242. self._readahead: BytesIO | None = None
  243. def close(self) -> None:
  244. """Close the underlying transport if a close function was provided."""
  245. if self._close:
  246. self._close()
  247. def __enter__(self) -> "Protocol":
  248. """Enter context manager."""
  249. return self
  250. def __exit__(
  251. self,
  252. exc_type: type[BaseException] | None,
  253. exc_val: BaseException | None,
  254. exc_tb: types.TracebackType | None,
  255. ) -> None:
  256. """Exit context manager and close transport."""
  257. self.close()
  258. def read_pkt_line(self) -> bytes | None:
  259. """Reads a pkt-line from the remote git process.
  260. This method may read from the readahead buffer; see unread_pkt_line.
  261. Returns: The next string from the stream, without the length prefix, or
  262. None for a flush-pkt ('0000') or delim-pkt ('0001').
  263. """
  264. if self._readahead is None:
  265. read = self.read
  266. else:
  267. read = self._readahead.read
  268. self._readahead = None
  269. try:
  270. sizestr = read(4)
  271. if not sizestr:
  272. raise HangupException
  273. size = int(sizestr, 16)
  274. if size == 0 or size == 1: # flush-pkt or delim-pkt
  275. if self.report_activity:
  276. self.report_activity(4, "read")
  277. return None
  278. if self.report_activity:
  279. self.report_activity(size, "read")
  280. pkt_contents = read(size - 4)
  281. except ConnectionResetError as exc:
  282. raise HangupException from exc
  283. except OSError as exc:
  284. raise GitProtocolError(str(exc)) from exc
  285. else:
  286. if len(pkt_contents) + 4 != size:
  287. raise GitProtocolError(
  288. f"Length of pkt read {len(pkt_contents) + 4:04x} does not match length prefix {size:04x}"
  289. )
  290. return pkt_contents
  291. def eof(self) -> bool:
  292. """Test whether the protocol stream has reached EOF.
  293. Note that this refers to the actual stream EOF and not just a
  294. flush-pkt.
  295. Returns: True if the stream is at EOF, False otherwise.
  296. """
  297. try:
  298. next_line = self.read_pkt_line()
  299. except HangupException:
  300. return True
  301. self.unread_pkt_line(next_line)
  302. return False
  303. def unread_pkt_line(self, data: bytes | None) -> None:
  304. """Unread a single line of data into the readahead buffer.
  305. This method can be used to unread a single pkt-line into a fixed
  306. readahead buffer.
  307. Args:
  308. data: The data to unread, without the length prefix.
  309. Raises:
  310. ValueError: If more than one pkt-line is unread.
  311. """
  312. if self._readahead is not None:
  313. raise ValueError("Attempted to unread multiple pkt-lines.")
  314. self._readahead = BytesIO(pkt_line(data))
  315. def read_pkt_seq(self) -> Iterable[bytes]:
  316. """Read a sequence of pkt-lines from the remote git process.
  317. Returns: Yields each line of data up to but not including the next
  318. flush-pkt.
  319. """
  320. pkt = self.read_pkt_line()
  321. while pkt:
  322. yield pkt
  323. pkt = self.read_pkt_line()
  324. def write_pkt_line(self, line: bytes | None) -> None:
  325. """Sends a pkt-line to the remote git process.
  326. Args:
  327. line: A string containing the data to send, without the length
  328. prefix.
  329. """
  330. try:
  331. line = pkt_line(line)
  332. self.write(line)
  333. if self.report_activity:
  334. self.report_activity(len(line), "write")
  335. except OSError as exc:
  336. raise GitProtocolError(str(exc)) from exc
  337. def write_sideband(self, channel: int, blob: bytes) -> None:
  338. """Write multiplexed data to the sideband.
  339. Args:
  340. channel: An int specifying the channel to write to.
  341. blob: A blob of data (as a string) to send on this channel.
  342. """
  343. # a pktline can be a max of 65520. a sideband line can therefore be
  344. # 65520-5 = 65515
  345. # WTF: Why have the len in ASCII, but the channel in binary.
  346. while blob:
  347. self.write_pkt_line(bytes(bytearray([channel])) + blob[:65515])
  348. blob = blob[65515:]
  349. def send_cmd(self, cmd: bytes, *args: bytes) -> None:
  350. """Send a command and some arguments to a git server.
  351. Only used for the TCP git protocol (git://).
  352. Args:
  353. cmd: The remote service to access.
  354. args: List of arguments to send to remove service.
  355. """
  356. self.write_pkt_line(format_cmd_pkt(cmd, *args))
  357. def read_cmd(self) -> tuple[bytes, list[bytes]]:
  358. """Read a command and some arguments from the git client.
  359. Only used for the TCP git protocol (git://).
  360. Returns: A tuple of (command, [list of arguments]).
  361. """
  362. line = self.read_pkt_line()
  363. if line is None:
  364. raise GitProtocolError("Expected command, got flush packet")
  365. return parse_cmd_pkt(line)
  366. _RBUFSIZE = 65536 # 64KB buffer for better network I/O performance
  367. class ReceivableProtocol(Protocol):
  368. """Variant of Protocol that allows reading up to a size without blocking.
  369. This class has a recv() method that behaves like socket.recv() in addition
  370. to a read() method.
  371. If you want to read n bytes from the wire and block until exactly n bytes
  372. (or EOF) are read, use read(n). If you want to read at most n bytes from
  373. the wire but don't care if you get less, use recv(n). Note that recv(n)
  374. will still block until at least one byte is read.
  375. """
  376. def __init__(
  377. self,
  378. recv: Callable[[int], bytes],
  379. write: Callable[[bytes], int | None],
  380. close: Callable[[], None] | None = None,
  381. report_activity: Callable[[int, str], None] | None = None,
  382. rbufsize: int = _RBUFSIZE,
  383. ) -> None:
  384. """Initialize ReceivableProtocol.
  385. Args:
  386. recv: Function to receive bytes from the transport
  387. write: Function to write bytes to the transport
  388. close: Optional function to close the transport
  389. report_activity: Optional function to report activity
  390. rbufsize: Read buffer size
  391. """
  392. super().__init__(self.read, write, close=close, report_activity=report_activity)
  393. self._recv = recv
  394. self._rbuf = BytesIO()
  395. self._rbufsize = rbufsize
  396. def read(self, size: int) -> bytes:
  397. """Read bytes from the socket.
  398. Args:
  399. size: Number of bytes to read
  400. Returns:
  401. Bytes read from socket
  402. """
  403. # From _fileobj.read in socket.py in the Python 2.6.5 standard library,
  404. # with the following modifications:
  405. # - omit the size <= 0 branch
  406. # - seek back to start rather than 0 in case some buffer has been
  407. # consumed.
  408. # - use SEEK_END instead of the magic number.
  409. # Copyright (c) 2001-2010 Python Software Foundation; All Rights
  410. # Reserved
  411. # Licensed under the Python Software Foundation License.
  412. # TODO: see if buffer is more efficient than cBytesIO.
  413. assert size > 0
  414. # Our use of BytesIO rather than lists of string objects returned by
  415. # recv() minimizes memory usage and fragmentation that occurs when
  416. # rbufsize is large compared to the typical return value of recv().
  417. buf = self._rbuf
  418. start = buf.tell()
  419. buf.seek(0, SEEK_END)
  420. # buffer may have been partially consumed by recv()
  421. buf_len = buf.tell() - start
  422. if buf_len >= size:
  423. # Already have size bytes in our buffer? Extract and return.
  424. buf.seek(start)
  425. rv = buf.read(size)
  426. self._rbuf = BytesIO()
  427. self._rbuf.write(buf.read())
  428. self._rbuf.seek(0)
  429. return rv
  430. self._rbuf = BytesIO() # reset _rbuf. we consume it via buf.
  431. while True:
  432. left = size - buf_len
  433. # recv() will malloc the amount of memory given as its
  434. # parameter even though it often returns much less data
  435. # than that. The returned data string is short lived
  436. # as we copy it into a BytesIO and free it. This avoids
  437. # fragmentation issues on many platforms.
  438. data = self._recv(left)
  439. if not data:
  440. break
  441. n = len(data)
  442. if n == size and not buf_len:
  443. # Shortcut. Avoid buffer data copies when:
  444. # - We have no data in our buffer.
  445. # AND
  446. # - Our call to recv returned exactly the
  447. # number of bytes we were asked to read.
  448. return data
  449. if n == left:
  450. buf.write(data)
  451. del data # explicit free
  452. break
  453. assert n <= left, f"_recv({left}) returned {n} bytes"
  454. buf.write(data)
  455. buf_len += n
  456. del data # explicit free
  457. # assert buf_len == buf.tell()
  458. buf.seek(start)
  459. return buf.read()
  460. def recv(self, size: int) -> bytes:
  461. """Receive bytes from the socket with buffering.
  462. Args:
  463. size: Maximum number of bytes to receive
  464. Returns:
  465. Bytes received from socket
  466. """
  467. assert size > 0
  468. buf = self._rbuf
  469. start = buf.tell()
  470. buf.seek(0, SEEK_END)
  471. buf_len = buf.tell()
  472. buf.seek(start)
  473. left = buf_len - start
  474. if not left:
  475. # only read from the wire if our read buffer is exhausted
  476. data = self._recv(self._rbufsize)
  477. if len(data) == size:
  478. # shortcut: skip the buffer if we read exactly size bytes
  479. return data
  480. buf = BytesIO()
  481. buf.write(data)
  482. buf.seek(0)
  483. del data # explicit free
  484. self._rbuf = buf
  485. return buf.read(size)
  486. def extract_capabilities(text: bytes) -> tuple[bytes, list[bytes]]:
  487. """Extract a capabilities list from a string, if present.
  488. Args:
  489. text: String to extract from
  490. Returns: Tuple with text with capabilities removed and list of capabilities
  491. """
  492. if b"\0" not in text:
  493. return text, []
  494. text, capabilities = text.rstrip().split(b"\0")
  495. return (text, capabilities.strip().split(b" "))
  496. def extract_want_line_capabilities(text: bytes) -> tuple[bytes, list[bytes]]:
  497. """Extract a capabilities list from a want line, if present.
  498. Note that want lines have capabilities separated from the rest of the line
  499. by a space instead of a null byte. Thus want lines have the form:
  500. want obj-id cap1 cap2 ...
  501. Args:
  502. text: Want line to extract from
  503. Returns: Tuple with text with capabilities removed and list of capabilities
  504. """
  505. split_text = text.rstrip().split(b" ")
  506. if len(split_text) < 3:
  507. return text, []
  508. return (b" ".join(split_text[:2]), split_text[2:])
  509. def ack_type(capabilities: Iterable[bytes]) -> int:
  510. """Extract the ack type from a capabilities list."""
  511. if b"multi_ack_detailed" in capabilities:
  512. return MULTI_ACK_DETAILED
  513. elif b"multi_ack" in capabilities:
  514. return MULTI_ACK
  515. return SINGLE_ACK
  516. class BufferedPktLineWriter:
  517. """Writer that wraps its data in pkt-lines and has an independent buffer.
  518. Consecutive calls to write() wrap the data in a pkt-line and then buffers
  519. it until enough lines have been written such that their total length
  520. (including length prefix) reach the buffer size.
  521. """
  522. def __init__(
  523. self, write: Callable[[bytes], int | None], bufsize: int = 65515
  524. ) -> None:
  525. """Initialize the BufferedPktLineWriter.
  526. Args:
  527. write: A write callback for the underlying writer.
  528. bufsize: The internal buffer size, including length prefixes.
  529. """
  530. self._write = write
  531. self._bufsize = bufsize
  532. self._wbuf = BytesIO()
  533. self._buflen = 0
  534. def write(self, data: bytes) -> None:
  535. """Write data, wrapping it in a pkt-line."""
  536. line = pkt_line(data)
  537. line_len = len(line)
  538. over = self._buflen + line_len - self._bufsize
  539. if over >= 0:
  540. start = line_len - over
  541. self._wbuf.write(line[:start])
  542. self.flush()
  543. else:
  544. start = 0
  545. saved = line[start:]
  546. self._wbuf.write(saved)
  547. self._buflen += len(saved)
  548. def flush(self) -> None:
  549. """Flush all data from the buffer."""
  550. data = self._wbuf.getvalue()
  551. if data:
  552. self._write(data)
  553. self._len = 0
  554. self._wbuf = BytesIO()
  555. class PktLineParser:
  556. """Packet line parser that hands completed packets off to a callback."""
  557. def __init__(self, handle_pkt: Callable[[bytes | None], None]) -> None:
  558. """Initialize PktLineParser.
  559. Args:
  560. handle_pkt: Callback function to handle completed packets
  561. """
  562. self.handle_pkt = handle_pkt
  563. self._readahead = BytesIO()
  564. def parse(self, data: bytes) -> None:
  565. """Parse a fragment of data and call back for any completed packets."""
  566. self._readahead.write(data)
  567. buf = self._readahead.getvalue()
  568. if len(buf) < 4:
  569. return
  570. while len(buf) >= 4:
  571. size = int(buf[:4], 16)
  572. if size == 0:
  573. self.handle_pkt(None)
  574. buf = buf[4:]
  575. elif size <= len(buf):
  576. self.handle_pkt(buf[4:size])
  577. buf = buf[size:]
  578. else:
  579. break
  580. self._readahead = BytesIO()
  581. self._readahead.write(buf)
  582. def get_tail(self) -> bytes:
  583. """Read back any unused data."""
  584. return self._readahead.getvalue()
  585. def format_capability_line(capabilities: Iterable[bytes]) -> bytes:
  586. """Format a capabilities list for the wire protocol.
  587. Args:
  588. capabilities: List of capability strings
  589. Returns:
  590. Space-separated capabilities as bytes
  591. """
  592. return b"".join([b" " + c for c in capabilities])
  593. def format_ref_line(
  594. ref: bytes, sha: bytes, capabilities: Sequence[bytes] | None = None
  595. ) -> bytes:
  596. """Format a ref advertisement line.
  597. Args:
  598. ref: Reference name
  599. sha: SHA hash
  600. capabilities: Optional list of capabilities
  601. Returns:
  602. Formatted ref line
  603. """
  604. if capabilities is None:
  605. return sha + b" " + ref + b"\n"
  606. else:
  607. return sha + b" " + ref + b"\0" + format_capability_line(capabilities) + b"\n"
  608. def format_shallow_line(sha: bytes) -> bytes:
  609. """Format a shallow line.
  610. Args:
  611. sha: SHA to mark as shallow
  612. Returns:
  613. Formatted shallow line
  614. """
  615. return COMMAND_SHALLOW + b" " + sha
  616. def format_unshallow_line(sha: bytes) -> bytes:
  617. """Format an unshallow line.
  618. Args:
  619. sha: SHA to unshallow
  620. Returns:
  621. Formatted unshallow line
  622. """
  623. return COMMAND_UNSHALLOW + b" " + sha
  624. def format_ack_line(sha: bytes, ack_type: bytes = b"") -> bytes:
  625. """Format an ACK line.
  626. Args:
  627. sha: SHA to acknowledge
  628. ack_type: Optional ACK type (e.g. b"continue")
  629. Returns:
  630. Formatted ACK line
  631. """
  632. if ack_type:
  633. ack_type = b" " + ack_type
  634. return b"ACK " + sha + ack_type + b"\n"
  635. def strip_peeled_refs(
  636. refs: "Mapping[Ref, ObjectID | None]",
  637. ) -> "dict[Ref, ObjectID | None]":
  638. """Remove all peeled refs from a refs dictionary.
  639. Args:
  640. refs: Dictionary of refs (may include peeled refs with ^{} suffix)
  641. Returns:
  642. Dictionary with peeled refs removed
  643. """
  644. return {
  645. ref: sha for (ref, sha) in refs.items() if not ref.endswith(PEELED_TAG_SUFFIX)
  646. }
  647. def split_peeled_refs(
  648. refs: "Mapping[Ref, ObjectID]",
  649. ) -> "tuple[dict[Ref, ObjectID], dict[Ref, ObjectID]]":
  650. """Split peeled refs from regular refs.
  651. Args:
  652. refs: Dictionary of refs (may include peeled refs with ^{} suffix)
  653. Returns:
  654. Tuple of (regular_refs, peeled_refs) where peeled_refs keys have
  655. the ^{} suffix removed
  656. """
  657. from .refs import Ref
  658. peeled: dict[Ref, ObjectID] = {}
  659. regular = {k: v for k, v in refs.items() if not k.endswith(PEELED_TAG_SUFFIX)}
  660. for ref, sha in refs.items():
  661. if ref.endswith(PEELED_TAG_SUFFIX):
  662. # Peeled refs are always ObjectID values
  663. peeled[Ref(ref[: -len(PEELED_TAG_SUFFIX)])] = sha
  664. return regular, peeled
  665. def write_info_refs(
  666. refs: "Mapping[Ref, ObjectID]", store: "ObjectContainer"
  667. ) -> "Iterator[bytes]":
  668. """Generate info refs in the format used by the dumb HTTP protocol.
  669. Args:
  670. refs: Dictionary of refs
  671. store: Object store to peel tags from
  672. Yields:
  673. Lines in info/refs format (sha + tab + refname)
  674. """
  675. from .object_store import peel_sha
  676. from .refs import HEADREF
  677. for name, sha in sorted(refs.items()):
  678. # get_refs() includes HEAD as a special case, but we don't want to
  679. # advertise it
  680. if name == HEADREF:
  681. continue
  682. try:
  683. o = store[sha]
  684. except KeyError:
  685. continue
  686. _unpeeled, peeled = peel_sha(store, sha)
  687. yield o.id + b"\t" + name + b"\n"
  688. if o.id != peeled.id:
  689. yield peeled.id + b"\t" + name + PEELED_TAG_SUFFIX + b"\n"
  690. def serialize_refs(
  691. store: "ObjectContainer", refs: "Mapping[Ref, ObjectID]"
  692. ) -> "dict[bytes, ObjectID]":
  693. """Serialize refs with peeled refs for Git protocol v0/v1.
  694. This function is used to prepare refs for transmission over the Git protocol.
  695. For tags, it includes both the tag object and the dereferenced object.
  696. Args:
  697. store: Object store to peel refs from
  698. refs: Dictionary of ref names to SHAs
  699. Returns:
  700. Dictionary with refs and peeled refs (marked with ^{})
  701. """
  702. import warnings
  703. from .object_store import peel_sha
  704. from .objects import Tag
  705. ret: dict[bytes, ObjectID] = {}
  706. for ref, sha in refs.items():
  707. try:
  708. unpeeled, peeled = peel_sha(store, ObjectID(sha))
  709. except KeyError:
  710. warnings.warn(
  711. "ref {} points at non-present sha {}".format(
  712. ref.decode("utf-8", "replace"), sha.decode("ascii")
  713. ),
  714. UserWarning,
  715. )
  716. continue
  717. else:
  718. if isinstance(unpeeled, Tag):
  719. ret[ref + PEELED_TAG_SUFFIX] = peeled.id
  720. ret[ref] = unpeeled.id
  721. return ret