objects.py 64 KB

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