objects.py 67 KB

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