objects.py 54 KB

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