objects.py 67 KB

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