protocol.py 24 KB

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