objects.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847
  1. # objects.py -- Access to base git objects
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008-2013 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. """Access to base git objects."""
  23. import binascii
  24. import os
  25. import posixpath
  26. import stat
  27. import sys
  28. import zlib
  29. from collections import namedtuple
  30. from collections.abc import Callable, Iterable, Iterator
  31. from hashlib import sha1
  32. from io import BufferedIOBase, BytesIO
  33. from typing import (
  34. IO,
  35. TYPE_CHECKING,
  36. Optional,
  37. Union,
  38. )
  39. if sys.version_info >= (3, 11):
  40. from typing import Self
  41. else:
  42. from typing_extensions import Self
  43. if sys.version_info >= (3, 10):
  44. from typing import TypeGuard # type: ignore
  45. else:
  46. from typing_extensions import TypeGuard
  47. from . import replace_me
  48. from .errors import (
  49. ChecksumMismatch,
  50. FileFormatException,
  51. NotBlobError,
  52. NotCommitError,
  53. NotTagError,
  54. NotTreeError,
  55. ObjectFormatException,
  56. )
  57. from .file import GitFile
  58. if TYPE_CHECKING:
  59. from _hashlib import HASH
  60. from .file import _GitFile
  61. ZERO_SHA = b"0" * 40
  62. # Header fields for commits
  63. _TREE_HEADER = b"tree"
  64. _PARENT_HEADER = b"parent"
  65. _AUTHOR_HEADER = b"author"
  66. _COMMITTER_HEADER = b"committer"
  67. _ENCODING_HEADER = b"encoding"
  68. _MERGETAG_HEADER = b"mergetag"
  69. _GPGSIG_HEADER = b"gpgsig"
  70. # Header fields for objects
  71. _OBJECT_HEADER = b"object"
  72. _TYPE_HEADER = b"type"
  73. _TAG_HEADER = b"tag"
  74. _TAGGER_HEADER = b"tagger"
  75. S_IFGITLINK = 0o160000
  76. MAX_TIME = 9223372036854775807 # (2**63) - 1 - signed long int max
  77. BEGIN_PGP_SIGNATURE = b"-----BEGIN PGP SIGNATURE-----"
  78. ObjectID = bytes
  79. class EmptyFileException(FileFormatException):
  80. """An unexpectedly empty file was encountered."""
  81. def S_ISGITLINK(m: int) -> bool:
  82. """Check if a mode indicates a submodule.
  83. Args:
  84. m: Mode to check
  85. Returns: a ``boolean``
  86. """
  87. return stat.S_IFMT(m) == S_IFGITLINK
  88. def _decompress(string: bytes) -> bytes:
  89. dcomp = zlib.decompressobj()
  90. dcomped = dcomp.decompress(string)
  91. dcomped += dcomp.flush()
  92. return dcomped
  93. def sha_to_hex(sha: ObjectID) -> bytes:
  94. """Takes a string and returns the hex of the sha within."""
  95. hexsha = binascii.hexlify(sha)
  96. assert len(hexsha) == 40, f"Incorrect length of sha1 string: {hexsha!r}"
  97. return hexsha
  98. def hex_to_sha(hex: Union[bytes, str]) -> bytes:
  99. """Takes a hex sha and returns a binary sha."""
  100. assert len(hex) == 40, f"Incorrect length of hexsha: {hex!r}"
  101. try:
  102. return binascii.unhexlify(hex)
  103. except TypeError as exc:
  104. if not isinstance(hex, bytes):
  105. raise
  106. raise ValueError(exc.args[0]) from exc
  107. def valid_hexsha(hex: Union[bytes, str]) -> bool:
  108. if len(hex) != 40:
  109. return False
  110. try:
  111. binascii.unhexlify(hex)
  112. except (TypeError, binascii.Error):
  113. return False
  114. else:
  115. return True
  116. def hex_to_filename(
  117. path: Union[str, bytes], hex: Union[str, bytes]
  118. ) -> Union[str, bytes]:
  119. """Takes a hex sha and returns its filename relative to the given path."""
  120. # os.path.join accepts bytes or unicode, but all args must be of the same
  121. # type. Make sure that hex which is expected to be bytes, is the same type
  122. # as path.
  123. if type(path) is not type(hex) and isinstance(path, str):
  124. hex = hex.decode("ascii") # type: ignore
  125. dir_name = hex[:2]
  126. file_name = hex[2:]
  127. # Check from object dir
  128. return os.path.join(path, dir_name, file_name) # type: ignore
  129. def filename_to_hex(filename: Union[str, bytes]) -> str:
  130. """Takes an object filename and returns its corresponding hex sha."""
  131. # grab the last (up to) two path components
  132. names = filename.rsplit(os.path.sep, 2)[-2:] # type: ignore
  133. errmsg = f"Invalid object filename: {filename!r}"
  134. assert len(names) == 2, errmsg
  135. base, rest = names
  136. assert len(base) == 2 and len(rest) == 38, errmsg
  137. hex_bytes = (base + rest).encode("ascii") # type: ignore
  138. hex_to_sha(hex_bytes)
  139. return hex_bytes.decode("ascii")
  140. def object_header(num_type: int, length: int) -> bytes:
  141. """Return an object header for the given numeric type and text length."""
  142. cls = object_class(num_type)
  143. if cls is None:
  144. raise AssertionError(f"unsupported class type num: {num_type}")
  145. return cls.type_name + b" " + str(length).encode("ascii") + b"\0"
  146. def serializable_property(name: str, docstring: Optional[str] = None) -> property:
  147. """A property that helps tracking whether serialization is necessary."""
  148. def set(obj: "ShaFile", value: object) -> None:
  149. setattr(obj, "_" + name, value)
  150. obj._needs_serialization = True
  151. def get(obj: "ShaFile") -> object:
  152. return getattr(obj, "_" + name)
  153. return property(get, set, doc=docstring)
  154. def object_class(type: Union[bytes, int]) -> Optional[type["ShaFile"]]:
  155. """Get the object class corresponding to the given type.
  156. Args:
  157. type: Either a type name string or a numeric type.
  158. Returns: The ShaFile subclass corresponding to the given type, or None if
  159. type is not a valid type name/number.
  160. """
  161. return _TYPE_MAP.get(type, None)
  162. def check_hexsha(hex: Union[str, bytes], error_msg: str) -> None:
  163. """Check if a string is a valid hex sha string.
  164. Args:
  165. hex: Hex string to check
  166. error_msg: Error message to use in exception
  167. Raises:
  168. ObjectFormatException: Raised when the string is not valid
  169. """
  170. if not valid_hexsha(hex):
  171. raise ObjectFormatException(f"{error_msg} {hex!r}")
  172. def check_identity(identity: Optional[bytes], error_msg: str) -> None:
  173. """Check if the specified identity is valid.
  174. This will raise an exception if the identity is not valid.
  175. Args:
  176. identity: Identity string
  177. error_msg: Error message to use in exception
  178. """
  179. if identity is None:
  180. raise ObjectFormatException(error_msg)
  181. email_start = identity.find(b"<")
  182. email_end = identity.find(b">")
  183. if not all(
  184. [
  185. email_start >= 1,
  186. identity[email_start - 1] == b" "[0],
  187. identity.find(b"<", email_start + 1) == -1,
  188. email_end == len(identity) - 1,
  189. b"\0" not in identity,
  190. b"\n" not in identity,
  191. ]
  192. ):
  193. raise ObjectFormatException(error_msg)
  194. def check_time(time_seconds: int) -> None:
  195. """Check if the specified time is not prone to overflow error.
  196. This will raise an exception if the time is not valid.
  197. Args:
  198. time_seconds: time in seconds
  199. """
  200. # Prevent overflow error
  201. if time_seconds > MAX_TIME:
  202. raise ObjectFormatException(f"Date field should not exceed {MAX_TIME}")
  203. def git_line(*items: bytes) -> bytes:
  204. """Formats items into a space separated line."""
  205. return b" ".join(items) + b"\n"
  206. class FixedSha:
  207. """SHA object that behaves like hashlib's but is given a fixed value."""
  208. __slots__ = ("_hexsha", "_sha")
  209. def __init__(self, hexsha: Union[str, bytes]) -> None:
  210. if isinstance(hexsha, str):
  211. hexsha = hexsha.encode("ascii") # type: ignore
  212. if not isinstance(hexsha, bytes):
  213. raise TypeError(f"Expected bytes for hexsha, got {hexsha!r}")
  214. self._hexsha = hexsha
  215. self._sha = hex_to_sha(hexsha)
  216. def digest(self) -> bytes:
  217. """Return the raw SHA digest."""
  218. return self._sha
  219. def hexdigest(self) -> str:
  220. """Return the hex SHA digest."""
  221. return self._hexsha.decode("ascii")
  222. # Type guard functions for runtime type narrowing
  223. if TYPE_CHECKING:
  224. def is_commit(obj: "ShaFile") -> TypeGuard["Commit"]:
  225. """Check if a ShaFile is a Commit."""
  226. return obj.type_name == b"commit"
  227. def is_tree(obj: "ShaFile") -> TypeGuard["Tree"]:
  228. """Check if a ShaFile is a Tree."""
  229. return obj.type_name == b"tree"
  230. def is_blob(obj: "ShaFile") -> TypeGuard["Blob"]:
  231. """Check if a ShaFile is a Blob."""
  232. return obj.type_name == b"blob"
  233. def is_tag(obj: "ShaFile") -> TypeGuard["Tag"]:
  234. """Check if a ShaFile is a Tag."""
  235. return obj.type_name == b"tag"
  236. else:
  237. # Runtime versions without type narrowing
  238. def is_commit(obj: "ShaFile") -> bool:
  239. """Check if a ShaFile is a Commit."""
  240. return obj.type_name == b"commit"
  241. def is_tree(obj: "ShaFile") -> bool:
  242. """Check if a ShaFile is a Tree."""
  243. return obj.type_name == b"tree"
  244. def is_blob(obj: "ShaFile") -> bool:
  245. """Check if a ShaFile is a Blob."""
  246. return obj.type_name == b"blob"
  247. def is_tag(obj: "ShaFile") -> bool:
  248. """Check if a ShaFile is a Tag."""
  249. return obj.type_name == b"tag"
  250. class ShaFile:
  251. """A git SHA file."""
  252. __slots__ = ("_chunked_text", "_needs_serialization", "_sha")
  253. _needs_serialization: bool
  254. type_name: bytes
  255. type_num: int
  256. _chunked_text: Optional[list[bytes]]
  257. _sha: Union[FixedSha, None, "HASH"]
  258. @staticmethod
  259. def _parse_legacy_object_header(
  260. magic: bytes, f: Union[BufferedIOBase, IO[bytes], "_GitFile"]
  261. ) -> "ShaFile":
  262. """Parse a legacy object, creating it but not reading the file."""
  263. bufsize = 1024
  264. decomp = zlib.decompressobj()
  265. header = decomp.decompress(magic)
  266. start = 0
  267. end = -1
  268. while end < 0:
  269. extra = f.read(bufsize)
  270. header += decomp.decompress(extra)
  271. magic += extra
  272. end = header.find(b"\0", start)
  273. start = len(header)
  274. header = header[:end]
  275. type_name, size = header.split(b" ", 1)
  276. try:
  277. int(size) # sanity check
  278. except ValueError as exc:
  279. raise ObjectFormatException(f"Object size not an integer: {exc}") from exc
  280. obj_class = object_class(type_name)
  281. if not obj_class:
  282. raise ObjectFormatException(
  283. "Not a known type: {}".format(type_name.decode("ascii"))
  284. )
  285. return obj_class()
  286. def _parse_legacy_object(self, map: bytes) -> None:
  287. """Parse a legacy object, setting the raw string."""
  288. text = _decompress(map)
  289. header_end = text.find(b"\0")
  290. if header_end < 0:
  291. raise ObjectFormatException("Invalid object header, no \\0")
  292. self.set_raw_string(text[header_end + 1 :])
  293. def as_legacy_object_chunks(self, compression_level: int = -1) -> Iterator[bytes]:
  294. """Return chunks representing the object in the experimental format.
  295. Returns: List of strings
  296. """
  297. compobj = zlib.compressobj(compression_level)
  298. yield compobj.compress(self._header())
  299. for chunk in self.as_raw_chunks():
  300. yield compobj.compress(chunk)
  301. yield compobj.flush()
  302. def as_legacy_object(self, compression_level: int = -1) -> bytes:
  303. """Return string representing the object in the experimental format."""
  304. return b"".join(
  305. self.as_legacy_object_chunks(compression_level=compression_level)
  306. )
  307. def as_raw_chunks(self) -> list[bytes]:
  308. """Return chunks with serialization of the object.
  309. Returns: List of strings, not necessarily one per line
  310. """
  311. if self._needs_serialization:
  312. self._sha = None
  313. self._chunked_text = self._serialize()
  314. self._needs_serialization = False
  315. return self._chunked_text # type: ignore
  316. def as_raw_string(self) -> bytes:
  317. """Return raw string with serialization of the object.
  318. Returns: String object
  319. """
  320. return b"".join(self.as_raw_chunks())
  321. def __bytes__(self) -> bytes:
  322. """Return raw string serialization of this object."""
  323. return self.as_raw_string()
  324. def __hash__(self) -> int:
  325. """Return unique hash for this object."""
  326. return hash(self.id)
  327. def as_pretty_string(self) -> str:
  328. """Return a string representing this object, fit for display."""
  329. return self.as_raw_string().decode("utf-8", "replace")
  330. def set_raw_string(self, text: bytes, sha: Optional[ObjectID] = None) -> None:
  331. """Set the contents of this object from a serialized string."""
  332. if not isinstance(text, bytes):
  333. raise TypeError(f"Expected bytes for text, got {text!r}")
  334. self.set_raw_chunks([text], sha)
  335. def set_raw_chunks(
  336. self, chunks: list[bytes], sha: Optional[ObjectID] = None
  337. ) -> None:
  338. """Set the contents of this object from a list of chunks."""
  339. self._chunked_text = chunks
  340. self._deserialize(chunks)
  341. if sha is None:
  342. self._sha = None
  343. else:
  344. self._sha = FixedSha(sha) # type: ignore
  345. self._needs_serialization = False
  346. @staticmethod
  347. def _parse_object_header(
  348. magic: bytes, f: Union[BufferedIOBase, IO[bytes], "_GitFile"]
  349. ) -> "ShaFile":
  350. """Parse a new style object, creating it but not reading the file."""
  351. num_type = (ord(magic[0:1]) >> 4) & 7
  352. obj_class = object_class(num_type)
  353. if not obj_class:
  354. raise ObjectFormatException(f"Not a known type {num_type}")
  355. return obj_class()
  356. def _parse_object(self, map: bytes) -> None:
  357. """Parse a new style object, setting self._text."""
  358. # skip type and size; type must have already been determined, and
  359. # we trust zlib to fail if it's otherwise corrupted
  360. byte = ord(map[0:1])
  361. used = 1
  362. while (byte & 0x80) != 0:
  363. byte = ord(map[used : used + 1])
  364. used += 1
  365. raw = map[used:]
  366. self.set_raw_string(_decompress(raw))
  367. @classmethod
  368. def _is_legacy_object(cls, magic: bytes) -> bool:
  369. b0 = ord(magic[0:1])
  370. b1 = ord(magic[1:2])
  371. word = (b0 << 8) + b1
  372. return (b0 & 0x8F) == 0x08 and (word % 31) == 0
  373. @classmethod
  374. def _parse_file(cls, f: Union[BufferedIOBase, IO[bytes], "_GitFile"]) -> "ShaFile":
  375. map = f.read()
  376. if not map:
  377. raise EmptyFileException("Corrupted empty file detected")
  378. if cls._is_legacy_object(map):
  379. obj = cls._parse_legacy_object_header(map, f)
  380. obj._parse_legacy_object(map)
  381. else:
  382. obj = cls._parse_object_header(map, f)
  383. obj._parse_object(map)
  384. return obj
  385. def __init__(self) -> None:
  386. """Don't call this directly."""
  387. self._sha = None
  388. self._chunked_text = []
  389. self._needs_serialization = True
  390. def _deserialize(self, chunks: list[bytes]) -> None:
  391. raise NotImplementedError(self._deserialize)
  392. def _serialize(self) -> list[bytes]:
  393. raise NotImplementedError(self._serialize)
  394. @classmethod
  395. def from_path(cls, path: Union[str, bytes]) -> "ShaFile":
  396. """Open a SHA file from disk."""
  397. with GitFile(path, "rb") as f:
  398. return cls.from_file(f)
  399. @classmethod
  400. def from_file(cls, f: Union[BufferedIOBase, IO[bytes], "_GitFile"]) -> "ShaFile":
  401. """Get the contents of a SHA file on disk."""
  402. try:
  403. obj = cls._parse_file(f)
  404. obj._sha = None
  405. return obj
  406. except (IndexError, ValueError) as exc:
  407. raise ObjectFormatException("invalid object header") from exc
  408. @staticmethod
  409. def from_raw_string(
  410. type_num: int, string: bytes, sha: Optional[ObjectID] = None
  411. ) -> "ShaFile":
  412. """Creates an object of the indicated type from the raw string given.
  413. Args:
  414. type_num: The numeric type of the object.
  415. string: The raw uncompressed contents.
  416. sha: Optional known sha for the object
  417. """
  418. cls = object_class(type_num)
  419. if cls is None:
  420. raise AssertionError(f"unsupported class type num: {type_num}")
  421. obj = cls()
  422. obj.set_raw_string(string, sha)
  423. return obj
  424. @staticmethod
  425. def from_raw_chunks(
  426. type_num: int, chunks: list[bytes], sha: Optional[ObjectID] = None
  427. ) -> "ShaFile":
  428. """Creates an object of the indicated type from the raw chunks given.
  429. Args:
  430. type_num: The numeric type of the object.
  431. chunks: An iterable of the raw uncompressed contents.
  432. sha: Optional known sha for the object
  433. """
  434. cls = object_class(type_num)
  435. if cls is None:
  436. raise AssertionError(f"unsupported class type num: {type_num}")
  437. obj = cls()
  438. obj.set_raw_chunks(chunks, sha)
  439. return obj
  440. @classmethod
  441. def from_string(cls, string: bytes) -> Self:
  442. """Create a ShaFile from a string."""
  443. obj = cls()
  444. obj.set_raw_string(string)
  445. return obj
  446. def _check_has_member(self, member: str, error_msg: str) -> None:
  447. """Check that the object has a given member variable.
  448. Args:
  449. member: the member variable to check for
  450. error_msg: the message for an error if the member is missing
  451. Raises:
  452. ObjectFormatException: with the given error_msg if member is
  453. missing or is None
  454. """
  455. if getattr(self, member, None) is None:
  456. raise ObjectFormatException(error_msg)
  457. def check(self) -> None:
  458. """Check this object for internal consistency.
  459. Raises:
  460. ObjectFormatException: if the object is malformed in some way
  461. ChecksumMismatch: if the object was created with a SHA that does
  462. not match its contents
  463. """
  464. # TODO: if we find that error-checking during object parsing is a
  465. # performance bottleneck, those checks should be moved to the class's
  466. # check() method during optimization so we can still check the object
  467. # when necessary.
  468. old_sha = self.id
  469. try:
  470. self._deserialize(self.as_raw_chunks())
  471. self._sha = None
  472. new_sha = self.id
  473. except Exception as exc:
  474. raise ObjectFormatException(exc) from exc
  475. if old_sha != new_sha:
  476. raise ChecksumMismatch(new_sha, old_sha)
  477. def _header(self) -> bytes:
  478. return object_header(self.type_num, self.raw_length())
  479. def raw_length(self) -> int:
  480. """Returns the length of the raw string of this object."""
  481. return sum(map(len, self.as_raw_chunks()))
  482. def sha(self) -> Union[FixedSha, "HASH"]:
  483. """The SHA1 object that is the name of this object."""
  484. if self._sha is None or self._needs_serialization:
  485. # this is a local because as_raw_chunks() overwrites self._sha
  486. new_sha = sha1()
  487. new_sha.update(self._header())
  488. for chunk in self.as_raw_chunks():
  489. new_sha.update(chunk)
  490. self._sha = new_sha
  491. return self._sha
  492. def copy(self) -> "ShaFile":
  493. """Create a new copy of this SHA1 object from its raw string."""
  494. obj_class = object_class(self.type_num)
  495. if obj_class is None:
  496. raise AssertionError(f"invalid type num {self.type_num}")
  497. return obj_class.from_raw_string(self.type_num, self.as_raw_string(), self.id)
  498. @property
  499. def id(self) -> bytes:
  500. """The hex SHA of this object."""
  501. return self.sha().hexdigest().encode("ascii")
  502. def __repr__(self) -> str:
  503. return f"<{self.__class__.__name__} {self.id!r}>"
  504. def __ne__(self, other: object) -> bool:
  505. """Check whether this object does not match the other."""
  506. return not isinstance(other, ShaFile) or self.id != other.id
  507. def __eq__(self, other: object) -> bool:
  508. """Return True if the SHAs of the two objects match."""
  509. return isinstance(other, ShaFile) and self.id == other.id
  510. def __lt__(self, other: object) -> bool:
  511. """Return whether SHA of this object is less than the other."""
  512. if not isinstance(other, ShaFile):
  513. raise TypeError
  514. return self.id < other.id
  515. def __le__(self, other: object) -> bool:
  516. """Check whether SHA of this object is less than or equal to the other."""
  517. if not isinstance(other, ShaFile):
  518. raise TypeError
  519. return self.id <= other.id
  520. class Blob(ShaFile):
  521. """A Git Blob object."""
  522. __slots__ = ()
  523. type_name = b"blob"
  524. type_num = 3
  525. _chunked_text: list[bytes]
  526. def __init__(self) -> None:
  527. super().__init__()
  528. self._chunked_text = []
  529. self._needs_serialization = False
  530. def _get_data(self) -> bytes:
  531. return self.as_raw_string()
  532. def _set_data(self, data: bytes) -> None:
  533. self.set_raw_string(data)
  534. data = property(
  535. _get_data, _set_data, doc="The text contained within the blob object."
  536. )
  537. def _get_chunked(self) -> list[bytes]:
  538. return self._chunked_text
  539. def _set_chunked(self, chunks: list[bytes]) -> None:
  540. self._chunked_text = chunks
  541. def _serialize(self) -> list[bytes]:
  542. return self._chunked_text
  543. def _deserialize(self, chunks: list[bytes]) -> None:
  544. self._chunked_text = chunks
  545. chunked = property(
  546. _get_chunked,
  547. _set_chunked,
  548. doc="The text in the blob object, as chunks (not necessarily lines)",
  549. )
  550. @classmethod
  551. def from_path(cls, path: Union[str, bytes]) -> "Blob":
  552. blob = ShaFile.from_path(path)
  553. if not isinstance(blob, cls):
  554. raise NotBlobError(path)
  555. return blob
  556. def check(self) -> None:
  557. """Check this object for internal consistency.
  558. Raises:
  559. ObjectFormatException: if the object is malformed in some way
  560. """
  561. super().check()
  562. def splitlines(self) -> list[bytes]:
  563. """Return list of lines in this blob.
  564. This preserves the original line endings.
  565. """
  566. chunks = self.chunked
  567. if not chunks:
  568. return []
  569. if len(chunks) == 1:
  570. return chunks[0].splitlines(True)
  571. remaining = None
  572. ret = []
  573. for chunk in chunks:
  574. lines = chunk.splitlines(True)
  575. if len(lines) > 1:
  576. ret.append((remaining or b"") + lines[0])
  577. ret.extend(lines[1:-1])
  578. remaining = lines[-1]
  579. elif len(lines) == 1:
  580. if remaining is None:
  581. remaining = lines.pop()
  582. else:
  583. remaining += lines.pop()
  584. if remaining is not None:
  585. ret.append(remaining)
  586. return ret
  587. def _parse_message(
  588. chunks: Iterable[bytes],
  589. ) -> Iterator[Union[tuple[None, None], tuple[Optional[bytes], bytes]]]:
  590. """Parse a message with a list of fields and a body.
  591. Args:
  592. chunks: the raw chunks of the tag or commit object.
  593. Returns: iterator of tuples of (field, value), one per header line, in the
  594. order read from the text, possibly including duplicates. Includes a
  595. field named None for the freeform tag/commit text.
  596. """
  597. f = BytesIO(b"".join(chunks))
  598. k = None
  599. v = b""
  600. eof = False
  601. def _strip_last_newline(value: bytes) -> bytes:
  602. """Strip the last newline from value."""
  603. if value and value.endswith(b"\n"):
  604. return value[:-1]
  605. return value
  606. # Parse the headers
  607. #
  608. # Headers can contain newlines. The next line is indented with a space.
  609. # We store the latest key as 'k', and the accumulated value as 'v'.
  610. for line in f:
  611. if line.startswith(b" "):
  612. # Indented continuation of the previous line
  613. v += line[1:]
  614. else:
  615. if k is not None:
  616. # We parsed a new header, return its value
  617. yield (k, _strip_last_newline(v))
  618. if line == b"\n":
  619. # Empty line indicates end of headers
  620. break
  621. (k, v) = line.split(b" ", 1)
  622. else:
  623. # We reached end of file before the headers ended. We still need to
  624. # return the previous header, then we need to return a None field for
  625. # the text.
  626. eof = True
  627. if k is not None:
  628. yield (k, _strip_last_newline(v))
  629. yield (None, None)
  630. if not eof:
  631. # We didn't reach the end of file while parsing headers. We can return
  632. # the rest of the file as a message.
  633. yield (None, f.read())
  634. f.close()
  635. def _format_message(
  636. headers: list[tuple[bytes, bytes]], body: Optional[bytes]
  637. ) -> Iterator[bytes]:
  638. for field, value in headers:
  639. lines = value.split(b"\n")
  640. yield git_line(field, lines[0])
  641. for line in lines[1:]:
  642. yield b" " + line + b"\n"
  643. yield b"\n" # There must be a new line after the headers
  644. if body:
  645. yield body
  646. class Tag(ShaFile):
  647. """A Git Tag object."""
  648. type_name = b"tag"
  649. type_num = 4
  650. __slots__ = (
  651. "_message",
  652. "_name",
  653. "_object_class",
  654. "_object_sha",
  655. "_signature",
  656. "_tag_time",
  657. "_tag_timezone",
  658. "_tag_timezone_neg_utc",
  659. "_tagger",
  660. )
  661. _message: Optional[bytes]
  662. _name: Optional[bytes]
  663. _object_class: Optional[type["ShaFile"]]
  664. _object_sha: Optional[bytes]
  665. _signature: Optional[bytes]
  666. _tag_time: Optional[int]
  667. _tag_timezone: Optional[int]
  668. _tag_timezone_neg_utc: Optional[bool]
  669. _tagger: Optional[bytes]
  670. def __init__(self) -> None:
  671. super().__init__()
  672. self._tagger = None
  673. self._tag_time = None
  674. self._tag_timezone = None
  675. self._tag_timezone_neg_utc = False
  676. self._signature: Optional[bytes] = None
  677. @classmethod
  678. def from_path(cls, filename: Union[str, bytes]) -> "Tag":
  679. tag = ShaFile.from_path(filename)
  680. if not isinstance(tag, cls):
  681. raise NotTagError(filename)
  682. return tag
  683. def check(self) -> None:
  684. """Check this object for internal consistency.
  685. Raises:
  686. ObjectFormatException: if the object is malformed in some way
  687. """
  688. super().check()
  689. assert self._chunked_text is not None
  690. self._check_has_member("_object_sha", "missing object sha")
  691. self._check_has_member("_object_class", "missing object type")
  692. self._check_has_member("_name", "missing tag name")
  693. if not self._name:
  694. raise ObjectFormatException("empty tag name")
  695. if self._object_sha is None:
  696. raise ObjectFormatException("missing object sha")
  697. check_hexsha(self._object_sha, "invalid object sha")
  698. if self._tagger is not None:
  699. check_identity(self._tagger, "invalid tagger")
  700. self._check_has_member("_tag_time", "missing tag time")
  701. if self._tag_time is None:
  702. raise ObjectFormatException("missing tag time")
  703. check_time(self._tag_time)
  704. last = None
  705. for field, _ in _parse_message(self._chunked_text):
  706. if field == _OBJECT_HEADER and last is not None:
  707. raise ObjectFormatException("unexpected object")
  708. elif field == _TYPE_HEADER and last != _OBJECT_HEADER:
  709. raise ObjectFormatException("unexpected type")
  710. elif field == _TAG_HEADER and last != _TYPE_HEADER:
  711. raise ObjectFormatException("unexpected tag name")
  712. elif field == _TAGGER_HEADER and last != _TAG_HEADER:
  713. raise ObjectFormatException("unexpected tagger")
  714. last = field
  715. def _serialize(self) -> list[bytes]:
  716. headers = []
  717. if self._object_sha is None:
  718. raise ObjectFormatException("missing object sha")
  719. headers.append((_OBJECT_HEADER, self._object_sha))
  720. if self._object_class is None:
  721. raise ObjectFormatException("missing object class")
  722. headers.append((_TYPE_HEADER, self._object_class.type_name))
  723. if self._name is None:
  724. raise ObjectFormatException("missing tag name")
  725. headers.append((_TAG_HEADER, self._name))
  726. if self._tagger:
  727. if self._tag_time is None:
  728. headers.append((_TAGGER_HEADER, self._tagger))
  729. else:
  730. if self._tag_timezone is None or self._tag_timezone_neg_utc is None:
  731. raise ObjectFormatException("missing timezone info")
  732. headers.append(
  733. (
  734. _TAGGER_HEADER,
  735. format_time_entry(
  736. self._tagger,
  737. self._tag_time,
  738. (self._tag_timezone, self._tag_timezone_neg_utc),
  739. ),
  740. )
  741. )
  742. if self.message is None and self._signature is None:
  743. body = None
  744. else:
  745. body = (self.message or b"") + (self._signature or b"")
  746. return list(_format_message(headers, body))
  747. def _deserialize(self, chunks: list[bytes]) -> None:
  748. """Grab the metadata attached to the tag."""
  749. self._tagger = None
  750. self._tag_time = None
  751. self._tag_timezone = None
  752. self._tag_timezone_neg_utc = False
  753. for field, value in _parse_message(chunks):
  754. if field == _OBJECT_HEADER:
  755. self._object_sha = value
  756. elif field == _TYPE_HEADER:
  757. assert isinstance(value, bytes)
  758. obj_class = object_class(value)
  759. if not obj_class:
  760. raise ObjectFormatException(f"Not a known type: {value!r}")
  761. self._object_class = obj_class
  762. elif field == _TAG_HEADER:
  763. self._name = value
  764. elif field == _TAGGER_HEADER:
  765. if value is None:
  766. raise ObjectFormatException("missing tagger value")
  767. (
  768. self._tagger,
  769. self._tag_time,
  770. (self._tag_timezone, self._tag_timezone_neg_utc),
  771. ) = parse_time_entry(value)
  772. elif field is None:
  773. if value is None:
  774. self._message = None
  775. self._signature = None
  776. else:
  777. try:
  778. sig_idx = value.index(BEGIN_PGP_SIGNATURE)
  779. except ValueError:
  780. self._message = value
  781. self._signature = None
  782. else:
  783. self._message = value[:sig_idx]
  784. self._signature = value[sig_idx:]
  785. else:
  786. raise ObjectFormatException(
  787. f"Unknown field {field.decode('ascii', 'replace')}"
  788. )
  789. def _get_object(self) -> tuple[type[ShaFile], bytes]:
  790. """Get the object pointed to by this tag.
  791. Returns: tuple of (object class, sha).
  792. """
  793. if self._object_class is None or self._object_sha is None:
  794. raise ValueError("Tag object is not properly initialized")
  795. return (self._object_class, self._object_sha)
  796. def _set_object(self, value: tuple[type[ShaFile], bytes]) -> None:
  797. (self._object_class, self._object_sha) = value
  798. self._needs_serialization = True
  799. object = property(_get_object, _set_object)
  800. name = serializable_property("name", "The name of this tag")
  801. tagger = serializable_property(
  802. "tagger", "Returns the name of the person who created this tag"
  803. )
  804. tag_time = serializable_property(
  805. "tag_time",
  806. "The creation timestamp of the tag. As the number of seconds since the epoch",
  807. )
  808. tag_timezone = serializable_property(
  809. "tag_timezone", "The timezone that tag_time is in."
  810. )
  811. message = serializable_property("message", "the message attached to this tag")
  812. signature = serializable_property("signature", "Optional detached GPG signature")
  813. def sign(self, keyid: Optional[str] = None) -> None:
  814. import gpg
  815. with gpg.Context(armor=True) as c:
  816. if keyid is not None:
  817. key = c.get_key(keyid)
  818. with gpg.Context(armor=True, signers=[key]) as ctx:
  819. self.signature, unused_result = ctx.sign(
  820. self.as_raw_string(),
  821. mode=gpg.constants.sig.mode.DETACH,
  822. )
  823. else:
  824. self.signature, unused_result = c.sign(
  825. self.as_raw_string(), mode=gpg.constants.sig.mode.DETACH
  826. )
  827. def raw_without_sig(self) -> bytes:
  828. """Return raw string serialization without the GPG/SSH signature.
  829. self.signature is a signature for the returned raw byte string serialization.
  830. """
  831. ret = self.as_raw_string()
  832. if self._signature:
  833. ret = ret[: -len(self._signature)]
  834. return ret
  835. def verify(self, keyids: Optional[Iterable[str]] = None) -> None:
  836. """Verify GPG signature for this tag (if it is signed).
  837. Args:
  838. keyids: Optional iterable of trusted keyids for this tag.
  839. If this tag is not signed by any key in keyids verification will
  840. fail. If not specified, this function only verifies that the tag
  841. has a valid signature.
  842. Raises:
  843. gpg.errors.BadSignatures: if GPG signature verification fails
  844. gpg.errors.MissingSignatures: if tag was not signed by a key
  845. specified in keyids
  846. """
  847. if self._signature is None:
  848. return
  849. import gpg
  850. with gpg.Context() as ctx:
  851. data, result = ctx.verify(
  852. self.raw_without_sig(),
  853. signature=self._signature,
  854. )
  855. if keyids:
  856. keys = [ctx.get_key(key) for key in keyids]
  857. for key in keys:
  858. for subkey in keys:
  859. for sig in result.signatures:
  860. if subkey.can_sign and subkey.fpr == sig.fpr:
  861. return
  862. raise gpg.errors.MissingSignatures(result, keys, results=(data, result))
  863. class TreeEntry(namedtuple("TreeEntry", ["path", "mode", "sha"])):
  864. """Named tuple encapsulating a single tree entry."""
  865. def in_path(self, path: bytes) -> "TreeEntry":
  866. """Return a copy of this entry with the given path prepended."""
  867. if not isinstance(self.path, bytes):
  868. raise TypeError(f"Expected bytes for path, got {path!r}")
  869. return TreeEntry(posixpath.join(path, self.path), self.mode, self.sha)
  870. def parse_tree(text: bytes, strict: bool = False) -> Iterator[tuple[bytes, int, bytes]]:
  871. """Parse a tree text.
  872. Args:
  873. text: Serialized text to parse
  874. Returns: iterator of tuples of (name, mode, sha)
  875. Raises:
  876. ObjectFormatException: if the object was malformed in some way
  877. """
  878. count = 0
  879. length = len(text)
  880. while count < length:
  881. mode_end = text.index(b" ", count)
  882. mode_text = text[count:mode_end]
  883. if strict and mode_text.startswith(b"0"):
  884. raise ObjectFormatException(f"Invalid mode {mode_text!r}")
  885. try:
  886. mode = int(mode_text, 8)
  887. except ValueError as exc:
  888. raise ObjectFormatException(f"Invalid mode {mode_text!r}") from exc
  889. name_end = text.index(b"\0", mode_end)
  890. name = text[mode_end + 1 : name_end]
  891. count = name_end + 21
  892. sha = text[name_end + 1 : count]
  893. if len(sha) != 20:
  894. raise ObjectFormatException("Sha has invalid length")
  895. hexsha = sha_to_hex(sha)
  896. yield (name, mode, hexsha)
  897. def serialize_tree(items: Iterable[tuple[bytes, int, bytes]]) -> Iterator[bytes]:
  898. """Serialize the items in a tree to a text.
  899. Args:
  900. items: Sorted iterable over (name, mode, sha) tuples
  901. Returns: Serialized tree text as chunks
  902. """
  903. for name, mode, hexsha in items:
  904. yield (
  905. (f"{mode:04o}").encode("ascii") + b" " + name + b"\0" + hex_to_sha(hexsha)
  906. )
  907. def sorted_tree_items(
  908. entries: dict[bytes, tuple[int, bytes]], name_order: bool
  909. ) -> Iterator[TreeEntry]:
  910. """Iterate over a tree entries dictionary.
  911. Args:
  912. name_order: If True, iterate entries in order of their name. If
  913. False, iterate entries in tree order, that is, treat subtree entries as
  914. having '/' appended.
  915. entries: Dictionary mapping names to (mode, sha) tuples
  916. Returns: Iterator over (name, mode, hexsha)
  917. """
  918. if name_order:
  919. key_func = key_entry_name_order
  920. else:
  921. key_func = key_entry
  922. for name, entry in sorted(entries.items(), key=key_func):
  923. mode, hexsha = entry
  924. # Stricter type checks than normal to mirror checks in the Rust version.
  925. mode = int(mode)
  926. if not isinstance(hexsha, bytes):
  927. raise TypeError(f"Expected bytes for SHA, got {hexsha!r}")
  928. yield TreeEntry(name, mode, hexsha)
  929. def key_entry(entry: tuple[bytes, tuple[int, ObjectID]]) -> bytes:
  930. """Sort key for tree entry.
  931. Args:
  932. entry: (name, value) tuple
  933. """
  934. (name, (mode, _sha)) = entry
  935. if stat.S_ISDIR(mode):
  936. name += b"/"
  937. return name
  938. def key_entry_name_order(entry: tuple[bytes, tuple[int, ObjectID]]) -> bytes:
  939. """Sort key for tree entry in name order."""
  940. return entry[0]
  941. def pretty_format_tree_entry(
  942. name: bytes, mode: int, hexsha: bytes, encoding: str = "utf-8"
  943. ) -> str:
  944. """Pretty format tree entry.
  945. Args:
  946. name: Name of the directory entry
  947. mode: Mode of entry
  948. hexsha: Hexsha of the referenced object
  949. Returns: string describing the tree entry
  950. """
  951. if mode & stat.S_IFDIR:
  952. kind = "tree"
  953. else:
  954. kind = "blob"
  955. return "{:04o} {} {}\t{}\n".format(
  956. mode,
  957. kind,
  958. hexsha.decode("ascii"),
  959. name.decode(encoding, "replace"),
  960. )
  961. class SubmoduleEncountered(Exception):
  962. """A submodule was encountered while resolving a path."""
  963. def __init__(self, path: bytes, sha: ObjectID) -> None:
  964. self.path = path
  965. self.sha = sha
  966. class Tree(ShaFile):
  967. """A Git tree object."""
  968. type_name = b"tree"
  969. type_num = 2
  970. __slots__ = "_entries"
  971. def __init__(self) -> None:
  972. super().__init__()
  973. self._entries: dict[bytes, tuple[int, bytes]] = {}
  974. @classmethod
  975. def from_path(cls, filename: Union[str, bytes]) -> "Tree":
  976. tree = ShaFile.from_path(filename)
  977. if not isinstance(tree, cls):
  978. raise NotTreeError(filename)
  979. return tree
  980. def __contains__(self, name: bytes) -> bool:
  981. return name in self._entries
  982. def __getitem__(self, name: bytes) -> tuple[int, ObjectID]:
  983. return self._entries[name]
  984. def __setitem__(self, name: bytes, value: tuple[int, ObjectID]) -> None:
  985. """Set a tree entry by name.
  986. Args:
  987. name: The name of the entry, as a string.
  988. value: A tuple of (mode, hexsha), where mode is the mode of the
  989. entry as an integral type and hexsha is the hex SHA of the entry as
  990. a string.
  991. """
  992. mode, hexsha = value
  993. self._entries[name] = (mode, hexsha)
  994. self._needs_serialization = True
  995. def __delitem__(self, name: bytes) -> None:
  996. del self._entries[name]
  997. self._needs_serialization = True
  998. def __len__(self) -> int:
  999. return len(self._entries)
  1000. def __iter__(self) -> Iterator[bytes]:
  1001. return iter(self._entries)
  1002. def add(self, name: bytes, mode: int, hexsha: bytes) -> None:
  1003. """Add an entry to the tree.
  1004. Args:
  1005. mode: The mode of the entry as an integral type. Not all
  1006. possible modes are supported by git; see check() for details.
  1007. name: The name of the entry, as a string.
  1008. hexsha: The hex SHA of the entry as a string.
  1009. """
  1010. self._entries[name] = mode, hexsha
  1011. self._needs_serialization = True
  1012. def iteritems(self, name_order: bool = False) -> Iterator[TreeEntry]:
  1013. """Iterate over entries.
  1014. Args:
  1015. name_order: If True, iterate in name order instead of tree
  1016. order.
  1017. Returns: Iterator over (name, mode, sha) tuples
  1018. """
  1019. return sorted_tree_items(self._entries, name_order)
  1020. def items(self) -> list[TreeEntry]:
  1021. """Return the sorted entries in this tree.
  1022. Returns: List with (name, mode, sha) tuples
  1023. """
  1024. return list(self.iteritems())
  1025. def _deserialize(self, chunks: list[bytes]) -> None:
  1026. """Grab the entries in the tree."""
  1027. try:
  1028. parsed_entries = parse_tree(b"".join(chunks))
  1029. except ValueError as exc:
  1030. raise ObjectFormatException(exc) from exc
  1031. # TODO: list comprehension is for efficiency in the common (small)
  1032. # case; if memory efficiency in the large case is a concern, use a
  1033. # genexp.
  1034. self._entries = {n: (m, s) for n, m, s in parsed_entries}
  1035. def check(self) -> None:
  1036. """Check this object for internal consistency.
  1037. Raises:
  1038. ObjectFormatException: if the object is malformed in some way
  1039. """
  1040. super().check()
  1041. assert self._chunked_text is not None
  1042. last = None
  1043. allowed_modes = (
  1044. stat.S_IFREG | 0o755,
  1045. stat.S_IFREG | 0o644,
  1046. stat.S_IFLNK,
  1047. stat.S_IFDIR,
  1048. S_IFGITLINK,
  1049. # TODO: optionally exclude as in git fsck --strict
  1050. stat.S_IFREG | 0o664,
  1051. )
  1052. for name, mode, sha in parse_tree(b"".join(self._chunked_text), True):
  1053. check_hexsha(sha, f"invalid sha {sha!r}")
  1054. if b"/" in name or name in (b"", b".", b"..", b".git"):
  1055. raise ObjectFormatException(
  1056. "invalid name {}".format(name.decode("utf-8", "replace"))
  1057. )
  1058. if mode not in allowed_modes:
  1059. raise ObjectFormatException(f"invalid mode {mode:06o}")
  1060. entry = (name, (mode, sha))
  1061. if last:
  1062. if key_entry(last) > key_entry(entry):
  1063. raise ObjectFormatException("entries not sorted")
  1064. if name == last[0]:
  1065. raise ObjectFormatException(f"duplicate entry {name!r}")
  1066. last = entry
  1067. def _serialize(self) -> list[bytes]:
  1068. return list(serialize_tree(self.iteritems()))
  1069. def as_pretty_string(self) -> str:
  1070. text: list[str] = []
  1071. for name, mode, hexsha in self.iteritems():
  1072. text.append(pretty_format_tree_entry(name, mode, hexsha))
  1073. return "".join(text)
  1074. def lookup_path(
  1075. self, lookup_obj: Callable[[ObjectID], ShaFile], path: bytes
  1076. ) -> tuple[int, ObjectID]:
  1077. """Look up an object in a Git tree.
  1078. Args:
  1079. lookup_obj: Callback for retrieving object by SHA1
  1080. path: Path to lookup
  1081. Returns: A tuple of (mode, SHA) of the resulting path.
  1082. """
  1083. # Handle empty path - return the tree itself
  1084. if not path:
  1085. return stat.S_IFDIR, self.id
  1086. parts = path.split(b"/")
  1087. sha = self.id
  1088. mode: Optional[int] = None
  1089. for i, p in enumerate(parts):
  1090. if not p:
  1091. continue
  1092. if mode is not None and S_ISGITLINK(mode):
  1093. raise SubmoduleEncountered(b"/".join(parts[:i]), sha)
  1094. obj = lookup_obj(sha)
  1095. if not isinstance(obj, Tree):
  1096. raise NotTreeError(sha)
  1097. mode, sha = obj[p]
  1098. if mode is None:
  1099. raise ValueError("No valid path found")
  1100. return mode, sha
  1101. def parse_timezone(text: bytes) -> tuple[int, bool]:
  1102. """Parse a timezone text fragment (e.g. '+0100').
  1103. Args:
  1104. text: Text to parse.
  1105. Returns: Tuple with timezone as seconds difference to UTC
  1106. and a boolean indicating whether this was a UTC timezone
  1107. prefixed with a negative sign (-0000).
  1108. """
  1109. # cgit parses the first character as the sign, and the rest
  1110. # as an integer (using strtol), which could also be negative.
  1111. # We do the same for compatibility. See #697828.
  1112. if text[0] not in b"+-":
  1113. raise ValueError("Timezone must start with + or - ({text})".format(**vars()))
  1114. sign = text[:1]
  1115. offset = int(text[1:])
  1116. if sign == b"-":
  1117. offset = -offset
  1118. unnecessary_negative_timezone = offset >= 0 and sign == b"-"
  1119. signum = ((offset < 0) and -1) or 1
  1120. offset = abs(offset)
  1121. hours = int(offset / 100)
  1122. minutes = offset % 100
  1123. return (
  1124. signum * (hours * 3600 + minutes * 60),
  1125. unnecessary_negative_timezone,
  1126. )
  1127. def format_timezone(offset: int, unnecessary_negative_timezone: bool = False) -> bytes:
  1128. """Format a timezone for Git serialization.
  1129. Args:
  1130. offset: Timezone offset as seconds difference to UTC
  1131. unnecessary_negative_timezone: Whether to use a minus sign for
  1132. UTC or positive timezones (-0000 and --700 rather than +0000 / +0700).
  1133. """
  1134. if offset % 60 != 0:
  1135. raise ValueError("Unable to handle non-minute offset.")
  1136. if offset < 0 or unnecessary_negative_timezone:
  1137. sign = "-"
  1138. offset = -offset
  1139. else:
  1140. sign = "+"
  1141. return ("%c%02d%02d" % (sign, offset / 3600, (offset / 60) % 60)).encode("ascii") # noqa: UP031
  1142. def parse_time_entry(
  1143. value: bytes,
  1144. ) -> tuple[bytes, Optional[int], tuple[Optional[int], bool]]:
  1145. """Parse event.
  1146. Args:
  1147. value: Bytes representing a git commit/tag line
  1148. Raises:
  1149. ObjectFormatException in case of parsing error (malformed
  1150. field date)
  1151. Returns: Tuple of (author, time, (timezone, timezone_neg_utc))
  1152. """
  1153. try:
  1154. sep = value.rindex(b"> ")
  1155. except ValueError:
  1156. return (value, None, (None, False))
  1157. try:
  1158. person = value[0 : sep + 1]
  1159. rest = value[sep + 2 :]
  1160. timetext, timezonetext = rest.rsplit(b" ", 1)
  1161. time = int(timetext)
  1162. timezone, timezone_neg_utc = parse_timezone(timezonetext)
  1163. except ValueError as exc:
  1164. raise ObjectFormatException(exc) from exc
  1165. return person, time, (timezone, timezone_neg_utc)
  1166. def format_time_entry(
  1167. person: bytes, time: int, timezone_info: tuple[int, bool]
  1168. ) -> bytes:
  1169. """Format an event."""
  1170. (timezone, timezone_neg_utc) = timezone_info
  1171. return b" ".join(
  1172. [person, str(time).encode("ascii"), format_timezone(timezone, timezone_neg_utc)]
  1173. )
  1174. @replace_me(since="0.21.0", remove_in="0.24.0")
  1175. def parse_commit(
  1176. chunks: Iterable[bytes],
  1177. ) -> tuple[
  1178. Optional[bytes],
  1179. list[bytes],
  1180. tuple[Optional[bytes], Optional[int], tuple[Optional[int], Optional[bool]]],
  1181. tuple[Optional[bytes], Optional[int], tuple[Optional[int], Optional[bool]]],
  1182. Optional[bytes],
  1183. list[Tag],
  1184. Optional[bytes],
  1185. Optional[bytes],
  1186. list[tuple[bytes, bytes]],
  1187. ]:
  1188. """Parse a commit object from chunks.
  1189. Args:
  1190. chunks: Chunks to parse
  1191. Returns: Tuple of (tree, parents, author_info, commit_info,
  1192. encoding, mergetag, gpgsig, message, extra)
  1193. """
  1194. parents = []
  1195. extra = []
  1196. tree = None
  1197. author_info: tuple[
  1198. Optional[bytes], Optional[int], tuple[Optional[int], Optional[bool]]
  1199. ] = (None, None, (None, None))
  1200. commit_info: tuple[
  1201. Optional[bytes], Optional[int], tuple[Optional[int], Optional[bool]]
  1202. ] = (None, None, (None, None))
  1203. encoding = None
  1204. mergetag = []
  1205. message = None
  1206. gpgsig = None
  1207. for field, value in _parse_message(chunks):
  1208. # TODO(jelmer): Enforce ordering
  1209. if field == _TREE_HEADER:
  1210. tree = value
  1211. elif field == _PARENT_HEADER:
  1212. if value is None:
  1213. raise ObjectFormatException("missing parent value")
  1214. parents.append(value)
  1215. elif field == _AUTHOR_HEADER:
  1216. if value is None:
  1217. raise ObjectFormatException("missing author value")
  1218. author_info = parse_time_entry(value)
  1219. elif field == _COMMITTER_HEADER:
  1220. if value is None:
  1221. raise ObjectFormatException("missing committer value")
  1222. commit_info = parse_time_entry(value)
  1223. elif field == _ENCODING_HEADER:
  1224. encoding = value
  1225. elif field == _MERGETAG_HEADER:
  1226. if value is None:
  1227. raise ObjectFormatException("missing mergetag value")
  1228. tag = Tag.from_string(value + b"\n")
  1229. assert isinstance(tag, Tag)
  1230. mergetag.append(tag)
  1231. elif field == _GPGSIG_HEADER:
  1232. gpgsig = value
  1233. elif field is None:
  1234. message = value
  1235. else:
  1236. if value is None:
  1237. raise ObjectFormatException(f"missing value for field {field!r}")
  1238. extra.append((field, value))
  1239. return (
  1240. tree,
  1241. parents,
  1242. author_info,
  1243. commit_info,
  1244. encoding,
  1245. mergetag,
  1246. gpgsig,
  1247. message,
  1248. extra,
  1249. )
  1250. class Commit(ShaFile):
  1251. """A git commit object."""
  1252. type_name = b"commit"
  1253. type_num = 1
  1254. __slots__ = (
  1255. "_author",
  1256. "_author_time",
  1257. "_author_timezone",
  1258. "_author_timezone_neg_utc",
  1259. "_commit_time",
  1260. "_commit_timezone",
  1261. "_commit_timezone_neg_utc",
  1262. "_committer",
  1263. "_encoding",
  1264. "_extra",
  1265. "_gpgsig",
  1266. "_mergetag",
  1267. "_message",
  1268. "_parents",
  1269. "_tree",
  1270. )
  1271. def __init__(self) -> None:
  1272. super().__init__()
  1273. self._parents: list[bytes] = []
  1274. self._encoding: Optional[bytes] = None
  1275. self._mergetag: list[Tag] = []
  1276. self._gpgsig: Optional[bytes] = None
  1277. self._extra: list[tuple[bytes, Optional[bytes]]] = []
  1278. self._author_timezone_neg_utc: Optional[bool] = False
  1279. self._commit_timezone_neg_utc: Optional[bool] = False
  1280. @classmethod
  1281. def from_path(cls, path: Union[str, bytes]) -> "Commit":
  1282. commit = ShaFile.from_path(path)
  1283. if not isinstance(commit, cls):
  1284. raise NotCommitError(path)
  1285. return commit
  1286. def _deserialize(self, chunks: list[bytes]) -> None:
  1287. self._parents = []
  1288. self._extra = []
  1289. self._tree = None
  1290. author_info: tuple[
  1291. Optional[bytes], Optional[int], tuple[Optional[int], Optional[bool]]
  1292. ] = (None, None, (None, None))
  1293. commit_info: tuple[
  1294. Optional[bytes], Optional[int], tuple[Optional[int], Optional[bool]]
  1295. ] = (None, None, (None, None))
  1296. self._encoding = None
  1297. self._mergetag = []
  1298. self._message = None
  1299. self._gpgsig = None
  1300. for field, value in _parse_message(chunks):
  1301. # TODO(jelmer): Enforce ordering
  1302. if field == _TREE_HEADER:
  1303. self._tree = value
  1304. elif field == _PARENT_HEADER:
  1305. assert value is not None
  1306. self._parents.append(value)
  1307. elif field == _AUTHOR_HEADER:
  1308. if value is None:
  1309. raise ObjectFormatException("missing author value")
  1310. author_info = parse_time_entry(value)
  1311. elif field == _COMMITTER_HEADER:
  1312. if value is None:
  1313. raise ObjectFormatException("missing committer value")
  1314. commit_info = parse_time_entry(value)
  1315. elif field == _ENCODING_HEADER:
  1316. self._encoding = value
  1317. elif field == _MERGETAG_HEADER:
  1318. assert value is not None
  1319. tag = Tag.from_string(value + b"\n")
  1320. assert isinstance(tag, Tag)
  1321. self._mergetag.append(tag)
  1322. elif field == _GPGSIG_HEADER:
  1323. self._gpgsig = value
  1324. elif field is None:
  1325. self._message = value
  1326. else:
  1327. self._extra.append((field, value))
  1328. (
  1329. self._author,
  1330. self._author_time,
  1331. (self._author_timezone, self._author_timezone_neg_utc),
  1332. ) = author_info
  1333. (
  1334. self._committer,
  1335. self._commit_time,
  1336. (self._commit_timezone, self._commit_timezone_neg_utc),
  1337. ) = commit_info
  1338. def check(self) -> None:
  1339. """Check this object for internal consistency.
  1340. Raises:
  1341. ObjectFormatException: if the object is malformed in some way
  1342. """
  1343. super().check()
  1344. assert self._chunked_text is not None
  1345. self._check_has_member("_tree", "missing tree")
  1346. self._check_has_member("_author", "missing author")
  1347. self._check_has_member("_committer", "missing committer")
  1348. self._check_has_member("_author_time", "missing author time")
  1349. self._check_has_member("_commit_time", "missing commit time")
  1350. for parent in self._parents:
  1351. check_hexsha(parent, "invalid parent sha")
  1352. assert self._tree is not None # checked by _check_has_member above
  1353. check_hexsha(self._tree, "invalid tree sha")
  1354. assert self._author is not None # checked by _check_has_member above
  1355. assert self._committer is not None # checked by _check_has_member above
  1356. check_identity(self._author, "invalid author")
  1357. check_identity(self._committer, "invalid committer")
  1358. assert self._author_time is not None # checked by _check_has_member above
  1359. assert self._commit_time is not None # checked by _check_has_member above
  1360. check_time(self._author_time)
  1361. check_time(self._commit_time)
  1362. last = None
  1363. for field, _ in _parse_message(self._chunked_text):
  1364. if field == _TREE_HEADER and last is not None:
  1365. raise ObjectFormatException("unexpected tree")
  1366. elif field == _PARENT_HEADER and last not in (
  1367. _PARENT_HEADER,
  1368. _TREE_HEADER,
  1369. ):
  1370. raise ObjectFormatException("unexpected parent")
  1371. elif field == _AUTHOR_HEADER and last not in (
  1372. _TREE_HEADER,
  1373. _PARENT_HEADER,
  1374. ):
  1375. raise ObjectFormatException("unexpected author")
  1376. elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER:
  1377. raise ObjectFormatException("unexpected committer")
  1378. elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER:
  1379. raise ObjectFormatException("unexpected encoding")
  1380. last = field
  1381. # TODO: optionally check for duplicate parents
  1382. def sign(self, keyid: Optional[str] = None) -> None:
  1383. import gpg
  1384. with gpg.Context(armor=True) as c:
  1385. if keyid is not None:
  1386. key = c.get_key(keyid)
  1387. with gpg.Context(armor=True, signers=[key]) as ctx:
  1388. self.gpgsig, unused_result = ctx.sign(
  1389. self.as_raw_string(),
  1390. mode=gpg.constants.sig.mode.DETACH,
  1391. )
  1392. else:
  1393. self.gpgsig, unused_result = c.sign(
  1394. self.as_raw_string(), mode=gpg.constants.sig.mode.DETACH
  1395. )
  1396. def raw_without_sig(self) -> bytes:
  1397. """Return raw string serialization without the GPG/SSH signature.
  1398. self.gpgsig is a signature for the returned raw byte string serialization.
  1399. """
  1400. tmp = self.copy()
  1401. assert isinstance(tmp, Commit)
  1402. tmp._gpgsig = None
  1403. tmp.gpgsig = None
  1404. return tmp.as_raw_string()
  1405. def verify(self, keyids: Optional[Iterable[str]] = None) -> None:
  1406. """Verify GPG signature for this commit (if it is signed).
  1407. Args:
  1408. keyids: Optional iterable of trusted keyids for this commit.
  1409. If this commit is not signed by any key in keyids verification will
  1410. fail. If not specified, this function only verifies that the commit
  1411. has a valid signature.
  1412. Raises:
  1413. gpg.errors.BadSignatures: if GPG signature verification fails
  1414. gpg.errors.MissingSignatures: if commit was not signed by a key
  1415. specified in keyids
  1416. """
  1417. if self._gpgsig is None:
  1418. return
  1419. import gpg
  1420. with gpg.Context() as ctx:
  1421. data, result = ctx.verify(
  1422. self.raw_without_sig(),
  1423. signature=self._gpgsig,
  1424. )
  1425. if keyids:
  1426. keys = [ctx.get_key(key) for key in keyids]
  1427. for key in keys:
  1428. for subkey in keys:
  1429. for sig in result.signatures:
  1430. if subkey.can_sign and subkey.fpr == sig.fpr:
  1431. return
  1432. raise gpg.errors.MissingSignatures(result, keys, results=(data, result))
  1433. def _serialize(self) -> list[bytes]:
  1434. headers = []
  1435. assert self._tree is not None
  1436. tree_bytes = self._tree.id if isinstance(self._tree, Tree) else self._tree
  1437. headers.append((_TREE_HEADER, tree_bytes))
  1438. for p in self._parents:
  1439. headers.append((_PARENT_HEADER, p))
  1440. assert self._author is not None
  1441. assert self._author_time is not None
  1442. assert self._author_timezone is not None
  1443. assert self._author_timezone_neg_utc is not None
  1444. headers.append(
  1445. (
  1446. _AUTHOR_HEADER,
  1447. format_time_entry(
  1448. self._author,
  1449. self._author_time,
  1450. (self._author_timezone, self._author_timezone_neg_utc),
  1451. ),
  1452. )
  1453. )
  1454. assert self._committer is not None
  1455. assert self._commit_time is not None
  1456. assert self._commit_timezone is not None
  1457. assert self._commit_timezone_neg_utc is not None
  1458. headers.append(
  1459. (
  1460. _COMMITTER_HEADER,
  1461. format_time_entry(
  1462. self._committer,
  1463. self._commit_time,
  1464. (self._commit_timezone, self._commit_timezone_neg_utc),
  1465. ),
  1466. )
  1467. )
  1468. if self.encoding:
  1469. headers.append((_ENCODING_HEADER, self.encoding))
  1470. for mergetag in self.mergetag:
  1471. headers.append((_MERGETAG_HEADER, mergetag.as_raw_string()[:-1]))
  1472. headers.extend(
  1473. (field, value) for field, value in self._extra if value is not None
  1474. )
  1475. if self.gpgsig:
  1476. headers.append((_GPGSIG_HEADER, self.gpgsig))
  1477. return list(_format_message(headers, self._message))
  1478. tree = serializable_property("tree", "Tree that is the state of this commit")
  1479. def _get_parents(self) -> list[bytes]:
  1480. """Return a list of parents of this commit."""
  1481. return self._parents
  1482. def _set_parents(self, value: list[bytes]) -> None:
  1483. """Set a list of parents of this commit."""
  1484. self._needs_serialization = True
  1485. self._parents = value
  1486. parents = property(
  1487. _get_parents,
  1488. _set_parents,
  1489. doc="Parents of this commit, by their SHA1.",
  1490. )
  1491. @replace_me(since="0.21.0", remove_in="0.24.0")
  1492. def _get_extra(self) -> list[tuple[bytes, Optional[bytes]]]:
  1493. """Return extra settings of this commit."""
  1494. return self._extra
  1495. extra = property(
  1496. _get_extra,
  1497. doc="Extra header fields not understood (presumably added in a "
  1498. "newer version of git). Kept verbatim so the object can "
  1499. "be correctly reserialized. For private commit metadata, use "
  1500. "pseudo-headers in Commit.message, rather than this field.",
  1501. )
  1502. author = serializable_property("author", "The name of the author of the commit")
  1503. committer = serializable_property(
  1504. "committer", "The name of the committer of the commit"
  1505. )
  1506. message = serializable_property("message", "The commit message")
  1507. commit_time = serializable_property(
  1508. "commit_time",
  1509. "The timestamp of the commit. As the number of seconds since the epoch.",
  1510. )
  1511. commit_timezone = serializable_property(
  1512. "commit_timezone", "The zone the commit time is in"
  1513. )
  1514. author_time = serializable_property(
  1515. "author_time",
  1516. "The timestamp the commit was written. As the number of "
  1517. "seconds since the epoch.",
  1518. )
  1519. author_timezone = serializable_property(
  1520. "author_timezone", "Returns the zone the author time is in."
  1521. )
  1522. encoding = serializable_property("encoding", "Encoding of the commit message.")
  1523. mergetag = serializable_property("mergetag", "Associated signed tag.")
  1524. gpgsig = serializable_property("gpgsig", "GPG Signature.")
  1525. OBJECT_CLASSES = (
  1526. Commit,
  1527. Tree,
  1528. Blob,
  1529. Tag,
  1530. )
  1531. _TYPE_MAP: dict[Union[bytes, int], type[ShaFile]] = {}
  1532. for cls in OBJECT_CLASSES:
  1533. _TYPE_MAP[cls.type_name] = cls
  1534. _TYPE_MAP[cls.type_num] = cls
  1535. # Hold on to the pure-python implementations for testing
  1536. _parse_tree_py = parse_tree
  1537. _sorted_tree_items_py = sorted_tree_items
  1538. try:
  1539. # Try to import Rust versions
  1540. from dulwich._objects import (
  1541. parse_tree as _parse_tree_rs,
  1542. )
  1543. from dulwich._objects import (
  1544. sorted_tree_items as _sorted_tree_items_rs,
  1545. )
  1546. except ImportError:
  1547. pass
  1548. else:
  1549. parse_tree = _parse_tree_rs
  1550. sorted_tree_items = _sorted_tree_items_rs