objects.py 53 KB

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