protocol.py 24 KB

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