objects.py 60 KB

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