protocol.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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, Sequence
  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_DEEPEN_SINCE = b"deepen-since"
  167. COMMAND_DEEPEN_NOT = b"deepen-not"
  168. COMMAND_SHALLOW = b"shallow"
  169. COMMAND_UNSHALLOW = b"unshallow"
  170. COMMAND_DONE = b"done"
  171. COMMAND_WANT = b"want"
  172. COMMAND_HAVE = b"have"
  173. def format_cmd_pkt(cmd: bytes, *args: bytes) -> bytes:
  174. """Format a command packet.
  175. Args:
  176. cmd: Command name
  177. *args: Command arguments
  178. Returns:
  179. Formatted command packet
  180. """
  181. return cmd + b" " + b"".join([(a + b"\0") for a in args])
  182. def parse_cmd_pkt(line: bytes) -> tuple[bytes, list[bytes]]:
  183. """Parse a command packet.
  184. Args:
  185. line: Command line to parse
  186. Returns:
  187. Tuple of (command, [arguments])
  188. """
  189. splice_at = line.find(b" ")
  190. cmd, args = line[:splice_at], line[splice_at + 1 :]
  191. assert args[-1:] == b"\x00"
  192. return cmd, args[:-1].split(b"\0")
  193. def pkt_line(data: Optional[bytes]) -> bytes:
  194. """Wrap data in a pkt-line.
  195. Args:
  196. data: The data to wrap, as a str or None.
  197. Returns: The data prefixed with its length in pkt-line format; if data was
  198. None, returns the flush-pkt ('0000').
  199. """
  200. if data is None:
  201. return b"0000"
  202. return ("%04x" % (len(data) + 4)).encode("ascii") + data
  203. def pkt_seq(*seq: Optional[bytes]) -> bytes:
  204. """Wrap a sequence of data in pkt-lines.
  205. Args:
  206. seq: An iterable of strings to wrap.
  207. """
  208. return b"".join([pkt_line(s) for s in seq]) + pkt_line(None)
  209. class Protocol:
  210. """Class for interacting with a remote git process over the wire.
  211. Parts of the git wire protocol use 'pkt-lines' to communicate. A pkt-line
  212. consists of the length of the line as a 4-byte hex string, followed by the
  213. payload data. The length includes the 4-byte header. The special line
  214. '0000' indicates the end of a section of input and is called a 'flush-pkt'.
  215. For details on the pkt-line format, see the cgit distribution:
  216. Documentation/technical/protocol-common.txt
  217. """
  218. def __init__(
  219. self,
  220. read: Callable[[int], bytes],
  221. write: Callable[[bytes], Optional[int]],
  222. close: Optional[Callable[[], None]] = None,
  223. report_activity: Optional[Callable[[int, str], None]] = None,
  224. ) -> None:
  225. """Initialize Protocol.
  226. Args:
  227. read: Function to read bytes from the transport
  228. write: Function to write bytes to the transport
  229. close: Optional function to close the transport
  230. report_activity: Optional function to report activity
  231. """
  232. self.read = read
  233. self.write = write
  234. self._close = close
  235. self.report_activity = report_activity
  236. self._readahead: Optional[BytesIO] = None
  237. def close(self) -> None:
  238. """Close the underlying transport if a close function was provided."""
  239. if self._close:
  240. self._close()
  241. def __enter__(self) -> "Protocol":
  242. """Enter context manager."""
  243. return self
  244. def __exit__(
  245. self,
  246. exc_type: Optional[type[BaseException]],
  247. exc_val: Optional[BaseException],
  248. exc_tb: Optional[types.TracebackType],
  249. ) -> None:
  250. """Exit context manager and close transport."""
  251. self.close()
  252. def read_pkt_line(self) -> Optional[bytes]:
  253. """Reads a pkt-line from the remote git process.
  254. This method may read from the readahead buffer; see unread_pkt_line.
  255. Returns: The next string from the stream, without the length prefix, or
  256. None for a flush-pkt ('0000') or delim-pkt ('0001').
  257. """
  258. if self._readahead is None:
  259. read = self.read
  260. else:
  261. read = self._readahead.read
  262. self._readahead = None
  263. try:
  264. sizestr = read(4)
  265. if not sizestr:
  266. raise HangupException
  267. size = int(sizestr, 16)
  268. if size == 0 or size == 1: # flush-pkt or delim-pkt
  269. if self.report_activity:
  270. self.report_activity(4, "read")
  271. return None
  272. if self.report_activity:
  273. self.report_activity(size, "read")
  274. pkt_contents = read(size - 4)
  275. except ConnectionResetError as exc:
  276. raise HangupException from exc
  277. except OSError as exc:
  278. raise GitProtocolError(str(exc)) from exc
  279. else:
  280. if len(pkt_contents) + 4 != size:
  281. raise GitProtocolError(
  282. f"Length of pkt read {len(pkt_contents) + 4:04x} does not match length prefix {size:04x}"
  283. )
  284. return pkt_contents
  285. def eof(self) -> bool:
  286. """Test whether the protocol stream has reached EOF.
  287. Note that this refers to the actual stream EOF and not just a
  288. flush-pkt.
  289. Returns: True if the stream is at EOF, False otherwise.
  290. """
  291. try:
  292. next_line = self.read_pkt_line()
  293. except HangupException:
  294. return True
  295. self.unread_pkt_line(next_line)
  296. return False
  297. def unread_pkt_line(self, data: Optional[bytes]) -> None:
  298. """Unread a single line of data into the readahead buffer.
  299. This method can be used to unread a single pkt-line into a fixed
  300. readahead buffer.
  301. Args:
  302. data: The data to unread, without the length prefix.
  303. Raises:
  304. ValueError: If more than one pkt-line is unread.
  305. """
  306. if self._readahead is not None:
  307. raise ValueError("Attempted to unread multiple pkt-lines.")
  308. self._readahead = BytesIO(pkt_line(data))
  309. def read_pkt_seq(self) -> Iterable[bytes]:
  310. """Read a sequence of pkt-lines from the remote git process.
  311. Returns: Yields each line of data up to but not including the next
  312. flush-pkt.
  313. """
  314. pkt = self.read_pkt_line()
  315. while pkt:
  316. yield pkt
  317. pkt = self.read_pkt_line()
  318. def write_pkt_line(self, line: Optional[bytes]) -> None:
  319. """Sends a pkt-line to the remote git process.
  320. Args:
  321. line: A string containing the data to send, without the length
  322. prefix.
  323. """
  324. try:
  325. line = pkt_line(line)
  326. self.write(line)
  327. if self.report_activity:
  328. self.report_activity(len(line), "write")
  329. except OSError as exc:
  330. raise GitProtocolError(str(exc)) from exc
  331. def write_sideband(self, channel: int, blob: bytes) -> None:
  332. """Write multiplexed data to the sideband.
  333. Args:
  334. channel: An int specifying the channel to write to.
  335. blob: A blob of data (as a string) to send on this channel.
  336. """
  337. # a pktline can be a max of 65520. a sideband line can therefore be
  338. # 65520-5 = 65515
  339. # WTF: Why have the len in ASCII, but the channel in binary.
  340. while blob:
  341. self.write_pkt_line(bytes(bytearray([channel])) + blob[:65515])
  342. blob = blob[65515:]
  343. def send_cmd(self, cmd: bytes, *args: bytes) -> None:
  344. """Send a command and some arguments to a git server.
  345. Only used for the TCP git protocol (git://).
  346. Args:
  347. cmd: The remote service to access.
  348. args: List of arguments to send to remove service.
  349. """
  350. self.write_pkt_line(format_cmd_pkt(cmd, *args))
  351. def read_cmd(self) -> tuple[bytes, list[bytes]]:
  352. """Read a command and some arguments from the git client.
  353. Only used for the TCP git protocol (git://).
  354. Returns: A tuple of (command, [list of arguments]).
  355. """
  356. line = self.read_pkt_line()
  357. if line is None:
  358. raise GitProtocolError("Expected command, got flush packet")
  359. return parse_cmd_pkt(line)
  360. _RBUFSIZE = 65536 # 64KB buffer for better network I/O performance
  361. class ReceivableProtocol(Protocol):
  362. """Variant of Protocol that allows reading up to a size without blocking.
  363. This class has a recv() method that behaves like socket.recv() in addition
  364. to a read() method.
  365. If you want to read n bytes from the wire and block until exactly n bytes
  366. (or EOF) are read, use read(n). If you want to read at most n bytes from
  367. the wire but don't care if you get less, use recv(n). Note that recv(n)
  368. will still block until at least one byte is read.
  369. """
  370. def __init__(
  371. self,
  372. recv: Callable[[int], bytes],
  373. write: Callable[[bytes], Optional[int]],
  374. close: Optional[Callable[[], None]] = None,
  375. report_activity: Optional[Callable[[int, str], None]] = None,
  376. rbufsize: int = _RBUFSIZE,
  377. ) -> None:
  378. """Initialize ReceivableProtocol.
  379. Args:
  380. recv: Function to receive bytes from the transport
  381. write: Function to write bytes to the transport
  382. close: Optional function to close the transport
  383. report_activity: Optional function to report activity
  384. rbufsize: Read buffer size
  385. """
  386. super().__init__(self.read, write, close=close, report_activity=report_activity)
  387. self._recv = recv
  388. self._rbuf = BytesIO()
  389. self._rbufsize = rbufsize
  390. def read(self, size: int) -> bytes:
  391. """Read bytes from the socket.
  392. Args:
  393. size: Number of bytes to read
  394. Returns:
  395. Bytes read from socket
  396. """
  397. # From _fileobj.read in socket.py in the Python 2.6.5 standard library,
  398. # with the following modifications:
  399. # - omit the size <= 0 branch
  400. # - seek back to start rather than 0 in case some buffer has been
  401. # consumed.
  402. # - use SEEK_END instead of the magic number.
  403. # Copyright (c) 2001-2010 Python Software Foundation; All Rights
  404. # Reserved
  405. # Licensed under the Python Software Foundation License.
  406. # TODO: see if buffer is more efficient than cBytesIO.
  407. assert size > 0
  408. # Our use of BytesIO rather than lists of string objects returned by
  409. # recv() minimizes memory usage and fragmentation that occurs when
  410. # rbufsize is large compared to the typical return value of recv().
  411. buf = self._rbuf
  412. start = buf.tell()
  413. buf.seek(0, SEEK_END)
  414. # buffer may have been partially consumed by recv()
  415. buf_len = buf.tell() - start
  416. if buf_len >= size:
  417. # Already have size bytes in our buffer? Extract and return.
  418. buf.seek(start)
  419. rv = buf.read(size)
  420. self._rbuf = BytesIO()
  421. self._rbuf.write(buf.read())
  422. self._rbuf.seek(0)
  423. return rv
  424. self._rbuf = BytesIO() # reset _rbuf. we consume it via buf.
  425. while True:
  426. left = size - buf_len
  427. # recv() will malloc the amount of memory given as its
  428. # parameter even though it often returns much less data
  429. # than that. The returned data string is short lived
  430. # as we copy it into a BytesIO and free it. This avoids
  431. # fragmentation issues on many platforms.
  432. data = self._recv(left)
  433. if not data:
  434. break
  435. n = len(data)
  436. if n == size and not buf_len:
  437. # Shortcut. Avoid buffer data copies when:
  438. # - We have no data in our buffer.
  439. # AND
  440. # - Our call to recv returned exactly the
  441. # number of bytes we were asked to read.
  442. return data
  443. if n == left:
  444. buf.write(data)
  445. del data # explicit free
  446. break
  447. assert n <= left, f"_recv({left}) returned {n} bytes"
  448. buf.write(data)
  449. buf_len += n
  450. del data # explicit free
  451. # assert buf_len == buf.tell()
  452. buf.seek(start)
  453. return buf.read()
  454. def recv(self, size: int) -> bytes:
  455. """Receive bytes from the socket with buffering.
  456. Args:
  457. size: Maximum number of bytes to receive
  458. Returns:
  459. Bytes received from socket
  460. """
  461. assert size > 0
  462. buf = self._rbuf
  463. start = buf.tell()
  464. buf.seek(0, SEEK_END)
  465. buf_len = buf.tell()
  466. buf.seek(start)
  467. left = buf_len - start
  468. if not left:
  469. # only read from the wire if our read buffer is exhausted
  470. data = self._recv(self._rbufsize)
  471. if len(data) == size:
  472. # shortcut: skip the buffer if we read exactly size bytes
  473. return data
  474. buf = BytesIO()
  475. buf.write(data)
  476. buf.seek(0)
  477. del data # explicit free
  478. self._rbuf = buf
  479. return buf.read(size)
  480. def extract_capabilities(text: bytes) -> tuple[bytes, list[bytes]]:
  481. """Extract a capabilities list from a string, if present.
  482. Args:
  483. text: String to extract from
  484. Returns: Tuple with text with capabilities removed and list of capabilities
  485. """
  486. if b"\0" not in text:
  487. return text, []
  488. text, capabilities = text.rstrip().split(b"\0")
  489. return (text, capabilities.strip().split(b" "))
  490. def extract_want_line_capabilities(text: bytes) -> tuple[bytes, list[bytes]]:
  491. """Extract a capabilities list from a want line, if present.
  492. Note that want lines have capabilities separated from the rest of the line
  493. by a space instead of a null byte. Thus want lines have the form:
  494. want obj-id cap1 cap2 ...
  495. Args:
  496. text: Want line to extract from
  497. Returns: Tuple with text with capabilities removed and list of capabilities
  498. """
  499. split_text = text.rstrip().split(b" ")
  500. if len(split_text) < 3:
  501. return text, []
  502. return (b" ".join(split_text[:2]), split_text[2:])
  503. def ack_type(capabilities: Iterable[bytes]) -> int:
  504. """Extract the ack type from a capabilities list."""
  505. if b"multi_ack_detailed" in capabilities:
  506. return MULTI_ACK_DETAILED
  507. elif b"multi_ack" in capabilities:
  508. return MULTI_ACK
  509. return SINGLE_ACK
  510. class BufferedPktLineWriter:
  511. """Writer that wraps its data in pkt-lines and has an independent buffer.
  512. Consecutive calls to write() wrap the data in a pkt-line and then buffers
  513. it until enough lines have been written such that their total length
  514. (including length prefix) reach the buffer size.
  515. """
  516. def __init__(
  517. self, write: Callable[[bytes], Optional[int]], bufsize: int = 65515
  518. ) -> None:
  519. """Initialize the BufferedPktLineWriter.
  520. Args:
  521. write: A write callback for the underlying writer.
  522. bufsize: The internal buffer size, including length prefixes.
  523. """
  524. self._write = write
  525. self._bufsize = bufsize
  526. self._wbuf = BytesIO()
  527. self._buflen = 0
  528. def write(self, data: bytes) -> None:
  529. """Write data, wrapping it in a pkt-line."""
  530. line = pkt_line(data)
  531. line_len = len(line)
  532. over = self._buflen + line_len - self._bufsize
  533. if over >= 0:
  534. start = line_len - over
  535. self._wbuf.write(line[:start])
  536. self.flush()
  537. else:
  538. start = 0
  539. saved = line[start:]
  540. self._wbuf.write(saved)
  541. self._buflen += len(saved)
  542. def flush(self) -> None:
  543. """Flush all data from the buffer."""
  544. data = self._wbuf.getvalue()
  545. if data:
  546. self._write(data)
  547. self._len = 0
  548. self._wbuf = BytesIO()
  549. class PktLineParser:
  550. """Packet line parser that hands completed packets off to a callback."""
  551. def __init__(self, handle_pkt: Callable[[Optional[bytes]], None]) -> None:
  552. """Initialize PktLineParser.
  553. Args:
  554. handle_pkt: Callback function to handle completed packets
  555. """
  556. self.handle_pkt = handle_pkt
  557. self._readahead = BytesIO()
  558. def parse(self, data: bytes) -> None:
  559. """Parse a fragment of data and call back for any completed packets."""
  560. self._readahead.write(data)
  561. buf = self._readahead.getvalue()
  562. if len(buf) < 4:
  563. return
  564. while len(buf) >= 4:
  565. size = int(buf[:4], 16)
  566. if size == 0:
  567. self.handle_pkt(None)
  568. buf = buf[4:]
  569. elif size <= len(buf):
  570. self.handle_pkt(buf[4:size])
  571. buf = buf[size:]
  572. else:
  573. break
  574. self._readahead = BytesIO()
  575. self._readahead.write(buf)
  576. def get_tail(self) -> bytes:
  577. """Read back any unused data."""
  578. return self._readahead.getvalue()
  579. def format_capability_line(capabilities: Iterable[bytes]) -> bytes:
  580. """Format a capabilities list for the wire protocol.
  581. Args:
  582. capabilities: List of capability strings
  583. Returns:
  584. Space-separated capabilities as bytes
  585. """
  586. return b"".join([b" " + c for c in capabilities])
  587. def format_ref_line(
  588. ref: bytes, sha: bytes, capabilities: Optional[Sequence[bytes]] = None
  589. ) -> bytes:
  590. """Format a ref advertisement line.
  591. Args:
  592. ref: Reference name
  593. sha: SHA hash
  594. capabilities: Optional list of capabilities
  595. Returns:
  596. Formatted ref line
  597. """
  598. if capabilities is None:
  599. return sha + b" " + ref + b"\n"
  600. else:
  601. return sha + b" " + ref + b"\0" + format_capability_line(capabilities) + b"\n"
  602. def format_shallow_line(sha: bytes) -> bytes:
  603. """Format a shallow line.
  604. Args:
  605. sha: SHA to mark as shallow
  606. Returns:
  607. Formatted shallow line
  608. """
  609. return COMMAND_SHALLOW + b" " + sha
  610. def format_unshallow_line(sha: bytes) -> bytes:
  611. """Format an unshallow line.
  612. Args:
  613. sha: SHA to unshallow
  614. Returns:
  615. Formatted unshallow line
  616. """
  617. return COMMAND_UNSHALLOW + b" " + sha
  618. def format_ack_line(sha: bytes, ack_type: bytes = b"") -> bytes:
  619. """Format an ACK line.
  620. Args:
  621. sha: SHA to acknowledge
  622. ack_type: Optional ACK type (e.g. b"continue")
  623. Returns:
  624. Formatted ACK line
  625. """
  626. if ack_type:
  627. ack_type = b" " + ack_type
  628. return b"ACK " + sha + ack_type + b"\n"