objects.py 67 KB

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